0

Why isn't the value of i (declared in the for loop) updating in the if condition (fmod(num, i)) with each iteration?

The function is supposed to return 1 if the argument passed to it is a prime number, otherwise it should return 0. int PrimeTest(int num) { if (num == 1) cout << "One is neither a prime nor a composite number." << endl; else if (num == 2) return 1; else if (num > 2) { for (int i = 2; i <= ceil(pow(num, 0.5)); i++) { if (fmod(num, i) == 0) // num is a composite number. return 0; else if (i == ceil(pow(i, 0.5))) // num is a prime number, indeed. return 1; } } }

22nd Jan 2017, 1:19 AM
NNNicomedes
NNNicomedes - avatar
5 Answers
+ 5
1. if number is 1 you are not returning any value so an error can crawl in your program. return 2 2. i <= ceil(pow(num, 0.5)) is not good.better i<=floor(pow(num, 0.5)) or even better i<=sqrt(num) 3. use {} after for loop as you have two statements 4. no requirement for that last condition. int PrimeTest(int num) { if (num == 1) { cout << "One is neither a prime nor a composite number." << endl; return 2;} else if (num == 2) return 1; else if (num > 2) { for (int i = 2; i<=sqrt(num); i++) { { if (fmod(num, i) == 0) // num is a composite number. return 0; } return 1; } } }
22nd Jan 2017, 3:26 AM
Megatron
Megatron - avatar
0
How do I update i in my if else block?
22nd Jan 2017, 1:32 AM
NNNicomedes
NNNicomedes - avatar
0
The for loop already have the update as a third parameter of its syntax. for(initial_value ; condition ; update) { statements ; } In your case the update of i is incrementing it by one on each iteration (i++). I wish I understood your question.
22nd Jan 2017, 1:34 AM
Ahmed Elzoughby
Ahmed Elzoughby - avatar
0
If you run the function, the i in the if else block will keep the value of 2, it won't update along with the loop
22nd Jan 2017, 1:38 AM
NNNicomedes
NNNicomedes - avatar
0
Thanks Megatron, now the function is working as intended!
22nd Jan 2017, 4:02 PM
NNNicomedes
NNNicomedes - avatar