Determine if a number is prime. If it is not, then display its largest factor in CSharp

Description

The following code shows how to determine if a number is prime. If it is not, then display its largest factor.

Example


 // w  ww.  j a va 2  s  .  co m
using System; 
 
public class MainClass {    
  public static void Main() {    
    int num; 
    int i; 
    int factor; 
    bool isprime; 
 
 
    for(num = 2; num < 20; num++) { 
      isprime = true;  
      factor = 0; 
 
      // see if num is evenly divisible 
      for(i=2; i <= num/2; i++) { 
        if((num % i) == 0) { 
          // num is evenly divisible -- not prime 
          isprime = false; 
          factor = i; 
        } 
      }  
      if(isprime) 
        Console.WriteLine(num + " is prime."); 
      else 
        Console.WriteLine("Largest factor of " + num + 
                          " is " + factor); 
    } 
  }    
}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception