Thread: Prime factorization of a number

1. Prime factorization of a number

So I am writing a code where the program will keep asking for a number and calculate its prime factorization unless the user enters 1 or less. What am I doing wrong?
Code:
```#include<stdio.h>
int main()
{
int x, i;

while (x > 1) {
printf("Enter an integer:  ");
scanf("%d", &x);
printf("The prime factorization of %d is ", x);

while (x % 2 == 0) {
printf("2 ");
x = x / 2;
}
for (i = 3; i < 1009; i = i + 2) {
while (x % i == 0) {
printf("%d ", i);
x = x / i;
}
}

}

return 0;
}```

2. How does it not work?

3. It terminates after computing for the first input.

4. Notice that your loop condition involves x, but you modify x after reading it. You need to check what the user entered immediately after reading it.

5. How do I fix that error?

6. One way that doesn't require so much changes would be to change your outer while loop condition to 1, i.e., true. This makes your loop an infinite loop, but then you add a check for the user input right after reading it, and if it is 1 or less, break from the loop.

7. What would that loop look like?

8. Um, I just told you.

Let's put it another way: why does your program "terminates after computing for the first input"?

9. Not sure if you have learned about functions yet, but they would make your task easier:
Code:
```#include <stdio.h>
#include <stdbool.h>

void print_prime_factors(int num)
{
printf("The prime factors of %d are ", num);
}

int main()
{
int num;
while(true)
{
printf("Enter an integer:  ");
scanf("%d", &num);
if (num < 2)
break;

print_prime_factors(num);
}

return 0;
}```