### Integer Factorization loop problem

Hello, people!
So i wrote a little program that should decompose numbers into smaller divisors (integer factorization), but when i was running it for the first time, i encountered a problem: the program was getting stuck after outputting first divisor. Here's the code btw:

 ``12345678910111213141516171819202122232425262728`` ``````#include int main() { using namespace std; cout << "Enter negative number to exit"; int i=2,input; while(true) { cout << "\nEnter a number to decompose: "; cin >> input; if (input<=0) break; while(input > 1) { if (input%i==0) { cout << input << "\t|\t" << i << endl; input /= i; }; if (input%i==0) i++; }; }; return 0; }``````

Appearantly it executes the if operators only once during the loop, but I don't know why. Any ideas?
Try this code

 ``1234567891011121314151617181920212223242526272829`` ``````#include using namespace std; int main() { cout << "Enter negative number to exit"; int i=2,input; while(true) { cout << "\nEnter a number to decompose: "; cin >> input; if (input<=0) break; while(input > 1) { if (input%i==0) { cout << input << "\t|\t" << i << endl; input /= i; } if (input%i==0) i++; } } return 0; } ``````
Didn't work, sorry. Results are the same.
This will work
 ``1234567891011121314`` ``````int main() { int n=1; int i=2,input; while(n>=0) { cout << "Enter negative number to exit"; cin>>n; ............... ................. } return; }``````
Lets say the input is 2.

while(2 > 1) //true

if(remainder of 2/2 == 0) //true

cout

input = 2 /2 //input now equals 1

if(remainder of 1/2 == 0) //false input equals 1 now, so there is a remainder

loop

while (1 > 1) //false; break

while(3 > 1) //true continue

if(remainder of 3/2 == 0) //false continue
if(remainder of 3/2 == 0)// false continue
while(3 > 1) //true continue

this is a infinite loop. Any odd number is going to produce this, and any even number is going to loop only once.

I think what you want is:

while(input%i == 0)

then on the second if statement
if(!input%i == 0) i++; //increment the variable to an even number
Try this:
 ``12345678910`` `````` while(input > 1) { if (input%i==0) { cout << input << "\t|\t" << i << endl; input /= i; continue; } i++; }``````

The `continue` at line 7 here means go back to the start of this `while` loop, hence `i` is not incremented, allowing for repeated factors.

Also, the value of `i` needs to be reset for each new user input.
Last edited on
@pogrady Exactly! Thank you! The code did work as intended.
@Chervil I did as pogrady said, but your code works too so thanks.
Topic archived. No new replies allowed.