I am very new to C++ and trying to create a code that allows me to see if a number is prime or not. I think I may be on the right track, but, when compiled and ran, it tells me that all numbers but one are prime. Could anyone point out my logical error and perhaps suggestions to fix it?
#include <iostream>
usingnamespace std;
int main () {
int num;
int divisor;
cout << "Enter a number please: ";
cin >> num;
while (divisor = 1, divisor < num, divisor++){
if (num / divisor == 0) {
cout << num << " is not prime. It is divisible by " << divisor << endl;}
else {cout << "You have a prime number!" << endl;
}
return 0;
}
}
Lines 14 and 15 almost make sense.
But you should use the modulo operator % instead of / (divide).
That determines the the number is not prime.
But line 16 (the else condition) is not correct.
For example, let's say you try to divide the number by 2. If there is no remainder, the number isn't prime. But if there is a remainder, does it mean it is prime? No, it simply means it is odd.
Okay. For line 16, is there a way to make the program loop, dividing each number by the divisor (which would work its way up from one)? That was my purpose for the while loop, to check and see if the number could be divided by anything other than 1 or the number itself without a remainder.