Click here to Skip to main content
15,919,500 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
int n;
            bool prime = true;
            Console.Read();
            for(int i=2;i<n-1;i++)>
            {
                if((n/i)==0)
                {prime=false;
                }
                break;}
            if(prime==true){
            Console.WriteLine("Yes the no. is prime");}
            else{
            Console.WriteLine("NO this is not prime");
            }
            }


    }
}

i want that whenever i write a prime number it show me message but i am getting problem in this code is right or not.how can i implement.
Posted
Updated 20-Aug-11 19:17pm
v2

1 solution

Your code will determine if a integer is a prime number or not, but not very efficiently, which might not matter if the prime numbers you're going to test are small.

You can easely optimize your code if you realize that N = Sqrt(N)*Sqrt(N) which means your loop condition would be i<=sqrt(n)
While this optimizes your code it's still not a good solution when you're gonna test big integers. The best algorithm, I know of, for determining whether an integer is a prime or not is the Miller-Rabin test[^]

Edit:
I just saw that your code actually isn't correct.
you'll need to initialize n ofcourse. and you're saying that n/i == 0 means that n is not a prime, that is not correct. If n%i == 0 then n is not a prime. You also have your break outside your if-block so your loop will stop after the first run through.
 
Share this answer
 
v5
Comments
thatraja 21-Aug-11 1:18am    
Fine, 5!
RaisKazi 21-Aug-11 1:32am    
Nicely Explained. 5
Sergey Alexandrovich Kryukov 21-Aug-11 21:54pm    
My 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900