I'm working on a program that lists a numbers prime factors.
I've finished the bulk of the work and all I have left is the first print where it says the number is prime or composite. I know the way I'm going at it is wrong because it wont work with an if or while.

int x;
int prime = 0;
cout << "Please enter a number: ";
cin >> x;
for (int i=2; i <= x; i++){
    if(x % i == 0){
        prime = 0;
        prime = 1;

if(prime = 1){
    cout << x << " is a PRIME number." << endl;
    cout << x << " is a COMPOSITE number." << endl;

I've looked at it and realize that no matter what I do no number is divisible by one less than it and because that is the last number in my loop it's always set to 1..
But, any suggestions on how to fix this?

6 Years
Discussion Span
Last Post by Megann1120

Set one value before you start testing.
Only reset the value when the condition you need to test for is met.

In this case, assume it's prime, set value to IsPrime.
During the test phase, any other factor sets the value to IsNotPrime.
At the end, if value is IsPrime, no other factors have been found.


In your program say i enter the number x=7

in your loop it goes

x(7)%i(2)!=0 so prime == 1
x(7)%i(3)!=0 so prime == 1
x(7)%i(4)!=0 so prime == 1 //needless since it cannot divide by 2
x(7)%i(5)!=0 so prime == 1
x(7)%i(6)!=0 so prime == 1 //same again
x(7)%i(7)==0 so prime == 0

If a number x, is not divisible by 2 then it can't be divisible by anything above x/2
If a number x, is not divisible by 2 or 3 then it can't be divisible by anything above x/3

Edited by frogboy77: n/a


if(prime = 1)

that's assigning 1 to prime, not checking equality of 1 with prime.

That was my problem, thanks!


Well, what I had was just from me messing around with it trying to get it to work. I know I had quite a few careless mistakes, but I fixed them all after I posted this.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.