Saturday, May 25, 2013

Write a method to find all prime numbers between 50 and 100

class Program
{
static void Main()
{
//Call the method to check for prime numbers and only print if the number is prime.
for (int x=50;  x<101 p="" x="">{
bool result = IsPrime(x);
if (result == true)
Console.Writeline("{0} is a prime number", x);
}
Console.ReadKey();
}

public static bool IsPrime(int n)
{
//negative numbers, 0 and 1 are not prime numbers
if ( n<= 1)
return false;

else
{
//you need to divide a number only by 2,3,5,7

int [] primeNumDivisors = new int[]{2,3,5,7};

foreach (int I in primeNumDivisors)
{
// no need to divide the number by itself
if ( n ! =I)
{
if (n% i ==0)
return false;
}
}
return true;
}
}
}
 


 

No comments: