Friday, February 4, 2011

Finding prime numbers in c++

Prime numbers are those numbers who have only two divisors , 1 and itself , Making a c++ program for prime numbers is too easy , you just have to check the number by dividing it with all the numbers from 1 to this number , if the remainder was zero for more than 2 times then the number isn't prim else number is prime.
Following is a program to find prime numbers between a range in c++

void main()
{
int num1=2,num2=10; // you can input these numbers from the user
int count=0;

for(int i=num1;i<=num2;i++)
{
count=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
{
count++;
}
else
{}
}

if(count==2)
{
cout<<"\nNumber "<}

}



}


LOGIC : divide each number with all the numbers from 1 to this given number , if its remainder comes 0 for 2 times then it is a prime number