I created a function for finding Prime Numbers, but the process takes a long time and uses a lot of memory. I need to optimize my code by making it more time and memory efficient.
The function is split into two parts:
The 1st part calculates odd numbers, the 2nd part is the isSimple
method which searches for odd numbers that are prime.
I made some progress by moving the Math.Sqrt(N)
outside of the for loop, but I'm not sure what to do next.
Any suggestions are welcome.
Program:
class Program
{
static void Main(string[] args)
{
//consider odd numbers
for (int i = 10001; i <=90000; i+=2)
{
if (isSimple(i))
{
Console.Write(i.ToString() + "\n");
}
}
}
//The method of finding primes
private static bool isSimple(int N)
{
double koren = Math.Sqrt(N);
// to verify a prime number or not enough to check whether it is //divisible number on numbers before its root
for (int i = 2; i <= koren; i++)
{
if (N % i == 0)
return false;
}
return true;
}
}