7-21 连续因子 (20分)
一个正整数 N 的因子中可能存在若干连续的数字。例如 630 可以分解为 3×5×6×7,其中 5、6、7 就是 3 个连续的数字。给定任一正整数 N,要求编写程序求出最长连续因子的个数,并输出最小的连续因子序列。
输入格式:
输入在一行中给出一个正整数 N(1<N<231)。
输出格式:
首先在第 1 行输出最长连续因子的个数;然后在第 2 行中按 因子1因子2……*因子k 的格式输出最小的连续因子序列,其中因子按递增顺序输出,1 不算在内。
输入样例:
630
输出样例:
3
567
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int N=sc.nextInt(); //输入所求的数字
int count=0; //计数器
int start=0; //标记起始位置
int m_count=0; //最大的因子个数
for(int i=2;i<=Math.sqrt(N);i++){
count=0;
int t=N;
int j=i;
while(t%j==0){
t=t/j;
j++;
count++;
}
if(count>m_count){
start=i;
m_count=count;
}
}
if(m_count!=0){
System.out.printf("%d\n",m_count);
for(int i=0;i<m_count;i++){
System.out.printf("%d",start+i);
if(i!=m_count-1)System.out.printf("*");
}
}
/*
千万不要忘记素数这种情况,如果输入的值是素数,那么它的因子就是 1 和它本身了,
但是题目要求1不能打印,所以我们最终只需输出它本身就可以了
*/
else System.out.printf("%d\n%d",1,N);
}
}