Find the smallest factor of a value and break out in CSharp

Description

The following code shows how to find the smallest factor of a value and break out.

Example


using System; /*ww  w  .j a  v a2s .  c  o m*/
 
public class MainClass {     
  public static void Main() {  
    int factor = 1; 
    int num = 1000; 
      
    for(int i=2; i < num/2; i++) {  
      if((num%i) == 0) { 
        factor = i; 
        break; // stop loop when factor is found 
      } 
    }  
    Console.WriteLine("Smallest factor is " + factor);  
  }  
}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




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