Title: It is well known that any composite (which is more than 1 and itself) can be written in several prime-number multiplication forms, which are called the composite's mass factor. For example, 24=2x2x2x3. The form of multiplying a composite into several prime numbers is called decomposition factorization. For a prime number, his qualitative factor can be defined as itself. Write a program to implement the decomposition factorization.
C + + implementation
1#include <iostream>2 3 using namespacestd;4 5 intIsPrime (intN) {6 for(inti =2; I < n; i++) {7 if(n%i = =0)8 return 0;9 }Ten return 1; One } A - intGetprimefactor (intN) {//you can return no value, where 1 indicates an error, and return 1 indicates normal. - if(N <2) the return-1; - if(IsPrime (n)) { -cout << N <<"\ t"; - return 1; + } - Else { + for(inti =2; I < n; i++) { A if(n%i = =0) { atcout << i <<"\ t"; -Getprimefactor (N/i); - Break; - } - } - } in return 1; - } to + intMainintargcChar*argv[]) { - intA; theCIN >>A; * Getprimefactor (a); $ GetChar ();Panax Notoginseng GetChar (); - return 0; the}
Idea: First write a function to determine whether a number is a prime, followed by a recursive method, a number divided by its minimum quality factor after the value is a quality factor decomposition of the value, the problem is the same size reduction, so is a recursive problem, the termination condition is that the number is a prime. It can be printed when it is a prime number or when a minimum quality factor is found.
Classical algorithm detailed (12) Decomposition factorization