L1-006. 連續因子
時間限制
400 ms
內存限制
65536 kB
代碼長度限制
8000 B
判題程序
Standard
作者
陳越
一個正整數N的因子中可能存在若干連續的數字。例如630可以分解為3*5*6*7,其中5、6、7就是3個連續的數字。給定任一正整數N,要求編寫程序求出最長連續因子的個數,並輸出最小的連續因子序列。(這里指,若有多個最長連續因子序列,輸出和最小的一組)
輸入格式:
輸入在一行中給出一個正整數N(1<N<231)。
輸出格式:
首先在第1行輸出最長連續因子的個數;然后在第2行中按“因子1*因子2*……*因子k”的格式輸出最小的連續因子序列,其中因子按遞增順序輸出,1不算在內。
輸入樣例:630輸出樣例:
3 5*6*7
分析:1.暴力法,從該數的sqrt(N)開始往前掃,不斷更新維護最長連續因子的個數並保存最小的連續因子序列
http://blog.csdn.net/liangzhaoyang1/article/details/51204989
#include "iostream" #include "cmath" #include "cstdio" #include "cstring" using namespace std; int main() { int Count,n,N,End,sq; char temp[1010],a[1010];///字符串存儲 便於拷貝get while(~scanf("%d",&N)) { End=1;n=0; sq=(int)sqrt(N)+1; for(int i=sq;i>=2&&End;i--) { Count=0; if(N%i==0) { temp[Count++]=i; int t=N/i; for(int j=i-1;j>=2;j--) { if(t%j==0) { temp[Count++]=j; t/=j; if(j==2) End=0; } else { temp[Count]=0;break; } } if(Count>=n) { strcpy(a,temp); n=Count; } } } if(n==0) printf("%d\n%d\n",1,N); else { printf("%d\n",n); for(int i=n-1;i>=0;i--) { printf("%d",a[i]); if(i!=0){ printf("*"); } else{ printf("\n"); } } } } return 0; }