Table of contents
- 1 Question
- 2 Analysis
- 3 Implementation
- 4 Running results
1 Question
Decompose a positive integer to the prime factor. For example: input 90 90 90, print it out 90 = 2 ∗ 3 ∗ 3 ∗ 5 90 = 2 * 3 * 3 * 5 90=2∗3∗3∗5
2 Analysis
The idea of decomposing the prime factor is to use this numbern
Continuously divided by an incremental numberi
(The number is initially2
, increment ton
) If it can be removedi
, then the current one isi
Just forn
one of the factors, thenn
Use this factor to narrow it, i.e.n=n/i
Repeat the above operation ifn = i
This means that the decomposition factor is over
3 Implementation
#include <>
int main() {
int n ;
printf("Please enter a positive integer:");
scanf("%d", &n);
printf("%d = ", n);
for (int i = 2; i <= n; i++) {
while(n != i) { // The execution conditions must be different from n and i. If they are equal, the decomposition will be completed.
if(n % i == 0) { // If the difference can be done, i is one of the factors that n
printf("%d * ", i); // Output factor
n = n / i; // A factor i is found, then n/i shrinks n and continues to search
} else {
break; // If you cannot separate it, you will jump out of this cycle and increment i to proceed to the next round
}
}
}
printf("%d\n", n); // The last remaining n cannot be divided into i, so it is also one of the factors, so the final output is
return 0;
}
4 Running results
Please enter a positive integer:120
120 = 2 * 2 * 2 * 3 * 5