思路:
每次从最小的质数开始相除,如果除开就再从最小的质数开始循环。
例题:
代码实现:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int a = n;
int ok = 0;
List<Integer>lists = new ArrayList<Integer>();
ff:for (int i = 2; i <=n; i++) {
for (int j = 2; j <=Math.sqrt(i); j++) {
if(i%j==0) {
ok=1;
break;
}
}
if(ok==0&a%i==0) {
lists.add(i);
a=a/i;
i=1;
if(a==0) {
break ff;
}
}
ok=0;
}
Object[]arr = lists.toArray();
System.out.print(n+"=");
for (int i = 0; i < arr.length; i++) {
if(i==0) {
System.out.print(arr[i]);
}else {
System.out.print("*"+arr[i]);
}
}
System.out.println();
}
}
}
关键步骤:
注意是 i<=n,必须带等于号。