inditify prime numbers

Updated jesse_gador143 0 Tallied Votes 230 Views Share
int number;
Console.Write("Enter a number: ");
number = int.Parse(Console.ReadLine());


int ctr = 2;
while(ctr <= number)
{
if(number % ctr == 0)
break;
ctr++;
}
if(ctr == number)
Console.WriteLine("Prime");
else
Console.WriteLine("Not Prime");

Console.ReadKey();

int number;
     Console.Write("Enter a number: ");
     number = int.Parse(Console.ReadLine());
     
     int ctr = 2;
     while(ctr <= number)
     {
           if(number % ctr == 0)
                break;
           ctr++;
     }
     if(ctr == number)
         Console.WriteLine("Prime");
     else
         Console.WriteLine("Not Prime");

     Console.ReadKey();
LizR 171 Posting Virtuoso

The short explaintion of a more efficient version:

When finding prime numbers, you should only test 2 and 3 to the square root of the number in increments of 2 (eg odd numbers), even if you arent going to use a list of generated prime numbers to reduce the time further.

int number;
     Console.Write("Enter a number: ");
     number = int.Parse(Console.ReadLine());
     
     int ctr = 2;
     int sq = (int)Math.Sqrt(number);
     while(ctr < sq)
     {
           if(number % ctr == 0)
                break;
           if (ctr==2) { ctr++; } else {ctr+=2;}
     }
     if(ctr == sq)
         Console.WriteLine("Prime");
     else
         Console.WriteLine("Not Prime as divides by "+ctr.ToString());

     Console.ReadKey();
ddanbe 2,724 Professional Procrastinator Featured Poster

LizR you are quite right using sqrt!
But!
Which is faster in the long run?
Counting to the number or counting to the sqrt of the number?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.