Thanks a lot, without a doubt that is my error...
But I tried n > i... and it give me an infinite loop... so now I dont know what to do
Well what are you TRYING to do with this loop? Go through all the numbers greater than or equal to n, but less than or equal to 100 or something similar? Go through numbers that are less than n? I don't understand the algorithm.
VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
Hello,
first a tip.
TO check whether a number 'n' is prime or not, it is just enuff to check whether n is divisible by any integer from 2 to n/2 . no need to loop till n-1.
As you will observe, for say a number 24, obviously no number greater than 12 can divide it. And that is true for all integers.
next, your code snippe ::
for (int n = 3; n <= 100; n++)
{
for (int i = 2; n < i; ++i)
{
newn = n % i;
while(newn > 0)
{
cout << n << " ";
}
}
}
if changed to
int flag=1;
for (int n = 3; n <= 100; n++)
{
for (int i = 2;i<= n/2; ++i)
{
newn = n % i;
if(newn==0)
{
flag=0;
break;
}
}
if (flag==1)
{
cout<<" "<<n;
}
flag=1;
}
The changes i made are ::
1. loop i from 2 till n/2
2. variable int flag.
-> set this to 1 at first , if none of the division gives a remainder 0, then it remains 1, meaning the number checked ( i ) is prime. else set it to 0 and break from inner loop.
it shud work.
regards
minigweek
Junior Poster in Training
68 posts since May 2007
Reputation Points: 97
Solved Threads: 5
Hello,
TO check whether a number 'n' is prime or not, it is just enuff to check whether n is divisible by any integer from 2 to n/2 . no need to loop till n-1.
As you will observe, for say a number 24, obviously no number greater than 12 can divide it. And that is true for all integers.
You actually only have to check up to the square root of n. Thus if you are testing, say, 97 for primality, the square root of 97 is 9.85, so if 97 is not prime, it must be divisible by an integer less than or equal to 9 (9.85 rounded down).
VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711