The following program determines prime variables. Values that return a remainder (p%d) for all values of d greater than 1 and less than p set the value of isPrime equal to “1”.
- (int)someMethod
{
@autoreleasepool {
int isPrime;
for (int p = 2; p <= 50; ++p) {
isPrime = 1;
for (int d = 2; d < p; ++d) {
if ( p % d == 0)
isPrime = 0;
if ( isPrime != 0)
NSLog (@"%i ", p);
}
}
}
return 0;
}
My question is, why is that the first “for” statement proceeds immediately after incrementing by “1” whereas in the 2nd “for” statement, the loop proceeds until the value of d is no longer less than p before moving on to the final “if” statement and NSLog.
If this question is not clear, for example, if the value of p is 14, the program proceeds as follows:
- p will increment by 1 to become 15
- the variable isPrime will be set to 1
- the value of d will be set to 2
- p%d will be calculated,
- the result will not be equal to 0, therefore the for statement will be skipped over
- THEN the value of d will, for some reason that I do not understand, increment to 3 and the loop will continue until d is equal to 15, INSTEAD of simply moving on to to the if statement and the NSLog, which would display “15”. Why is it that the second “for” loop continues to loop within the “if” statement, incrementing d, whereas the first loop increments p once and then moves on?
He understands for loops. It seems the other answers fail to understand the question. This loop does not correctly determine prime numbers at all. For instance, it prints out 15 as well as 49 as being prime, when they are not. Because it does printing in the inner loop it also prints out prime numbers multiple times. It SHOULD be printing out 15, and your logic is sound. I don’t know why it’s not for you, but it is for me. The correct implementation should be:
I’ll explain why it doesn’t work.
To determine if a number is prime or not, this program should see if any number divides evenly into
p. As soon as it finds one that does, the number is no longer prime, and it should setisPrimeto0. Once it’s checked every number less thanp, and thus determinedisPrime, it should checkisPrimeto see whether or not it should print the number out. However, it instead checksisPrimeevery time it checks to see if a number divides evenly intop. SinceisPrimeis set to 1 at the start for every value ofp, any number not divisible by 2 gets printed out. It checks to see if 2 evenly divides, it doesn’t, it immediately checksisPrimewhich is 1, and immediately prints it out, as if it’s prime; but what if a number AFTER 2 divides evenly into that number? This is why 15 and 49 are printed as prime numbers, when they are composite.