思路是 用一个数组存储所有的分解项 随后不断比较更新得到长度最大的最小序列 细节写在注释里了
代码如下:
import java.util.*;
public class PTA {
// arr:数据到2的31次方 数组开到31,用来存储分解出来的项
// Sequence:最终的目标数组
public static int[] arr=new int[31],Sequence;
//Begin:最小序列开始索引
//Max:最小序列最大长度
public static int Begin,Max=0;
//计算最小序列开始索引及最大长度的方法
//第一个参数是全局数组arr 第二个参数是它的长度
public static void Count(int[] arr,int index){
//不断判断begin与Begin max与Max 更新全局变量
int begin = 0,max = 0,count =1;
//遍历arr数组,如果连续,在计数器里加1
for(int i=0;i<index;i++){
if(arr[i]+1==arr[i+1]){
count++;
}
//如果间断,更新max,begin 并重新开始计数
else{
if(max < count){
max = count;
begin = i-max+1;
}
count=1;
}
}
//更新Max和Begin,把对应的数组复制到最终的Sequence数组中
if(Max<max){
Max = max;
Begin = begin;
Sequence = new int[Max];
System.arraycopy(arr, Begin, Sequence, 0, Max);
}
}
//分解质因数方法
//第一个参数index 指的是当前arr数组中的索引值;current 指的是本次递归中分解的初值; rest 指的是剩余的值
public static void decompose(int index,int current,int rest){
//递归基 分解完毕调用Count方法进行计数
if(rest==1){
Count(arr,index);
}
else{
//从本次分解初值current开始,一直到剩余值开始分解
for(int i=current;i<=rest;i++){
//判断是否能分
if(rest % i == 0){
//把分出来的数存到arr数组中
arr[index]=i;
//保证升序,让下一次分解的值不要小于本次分解的值
current = i;
//调用递归方法 继续分解
decompose(index+1,current,rest/i);
}
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n =scan.nextInt();
decompose(0,2,n);
//按照格式打印
System.out.println(Max);
for(int i=0;i<Max;i++){
if(i!=Max-1){
System.out.print(Sequence[i]+"*");
}
else{
System.out.print(Sequence[i]);
}
}
}
}
结果如下
请问这样做有什么问题?