Java code for factoring a positive integer into a prime factor
- 2020-06-12 09:03:14
- OfStack
Program analysis: to decompose the prime factor of n, the smallest prime number k should be found first, and then completed according to the following steps:
1. If the prime number is exactly equal to n, then the decomposition of the prime factors has been completed, just print it out.
2. If n < > k, but n is divisible by k, print out the value of k and use the quotient of n divided by k as the new positive integer you repeat step 1.
3. If n is not divisible by k, use k+1 as the value of k and repeat step 1.
Program design:
public class exp2{
public exp2(){}
public void fengjie(int n){
for(int i=2;i<=n/2;i++){
if(n%i==0){
System.out.print(i+"*");
fengjie(n/i);
}
}
System.out.print(n);
System.exit(0);/// Do not omit this sentence, or the result will be wrong
}
public static void main(String[] args){
String str="";
exp2 c=new exp2();
str=javax.swing.JOptionPane.showInputDialog(" Please enter the N Value of (input exit Exit) : ");
int N;
N=0;
try{
N=Integer.parseInt(str);
}catch(NumberFormatException e){
e.printStackTrace();
}
System.out.print(N+" Factorization prime factor: "+N+"=");
c.fengjie(N);
}
}