题目描述:
Among all the factors of a positive integer N, there may exist several consecutive numbers. For example, 630 can be factored as 3×5×6×7, where 5, 6, and 7 are the three consecutive numbers. Now given any positive N, you are supposed to find the maximum number of consecutive factors, and list the smallest sequence of the consecutive factors.
Input Specification:
Each input file contains one test case, which gives the integer N (1<N<2
31
).
Output Specification:
For each test case, print in the first line the maximum number of consecutive factors. Then in the second line, print the smallest sequence of the consecutive factors in the format , where the factors are listed in increasing order, and 1 is NOT included.factor[1]factor[2]…*factor[k]
Sample Input:
630
Sample Output:
3 5*6*7
解题思路及代码:
双重循环,记录最长序列以及开始位置
注意:1不是因数,对于类似2的输入,一定要输出自己本身;
import java.util.Scanner; public class ConsecutiveFactors连续因素 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int max=0,start=1; for(int i=2;i<=Math.sqrt(n);i++) { int s=i; int j=i+1; int temp = 0; while(n%s==0) { temp++; s=s*j; j++; } if(temp>max) { max=temp; start=i; } } if(max==0) { System.out.println("1"); System.out.println(n); } else { System.out.println(max); for(int i=0,j=start;i<max;i++,j++) if(i==0) System.out.print(j); else System.out.print("*"+j); } } }