I am new to C++ and coding, so excuse me if my knowledge is poor. I thought of a way to check if a number is prime (my code is below). My idea is that the user inputs a number, and uses a for
loop with a variable i
increasing in +1
increments until it equals to the inputted number. Each time this increment happens, i
is tested for being a factor of the inputted number. If it's a factor, the result of the modulus operator will be zero. In this case a variable remainders
is incremented by +1
, and, after all the values for i
have been tested, if the value of remainders
is 2, the tested number is prime, otherwise it is not prime. My code is below, please inform me whether my idea is correct.
#include <iostream>
using namespace std;
int main () {
int userNumber;
int remainders = 0;
cout << "Input the number to be tested:";
cin >> userNumber;
for (int i = 0; i == userNumber; i++){
int remainderTest = userNumber % i;
if (remainderTest = 0) {
remainders ++;
}
}
if (remainders == 2) {
cout << "The number you inputted is prime!";
} else {
cout << "The number you entered is not prime!";
}
return 0;
}