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
题目思路:连续的数字很容易联想到阶乘,阶层给人的惯性思维就是n*n-1*n-2*....*1,但是此题又不是简单的从1-n的阶乘,因为题目中有中间的连续数字并且不是都是从1开始的。所以想到用for(int i = 2; i < sqrt(n); i++)在这个循环中一直往后面乘,用循环里面的控制条件对应相应的几个连续数。
AC代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<climits>
#include<cmath>
using namespace std;
int main()
{
int n;
while(scanf("%d",&n) != EOF)
{
int k = 0,count = 0;
for(int i = 2; i < sqrt(n); i++)
{
long long ans = 1;//注意相乘可能会溢出!!!
for(int j = i; ans*j <= n; j++)//读者可仔细思考为什么用ans*j而不是ans
{
ans = ans*j;
if(n%ans == 0)//每一次都判断是否能被整除
{
if(count < j-i+1)//取最长的序列
{
k = i;
count = j-i+1;
}
}
}
}
if(count == 0)//特殊情况
printf("1\n%d\n",n);
else
{
printf("%d\n",count);
count = count+k;
for(int i = k; i < count-1; i++)
{
printf("%d*",i);
}
printf("%d\n",count-1);
}
}
return 0;
}
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<climits>
#include<cmath>
using namespace std;
int main()
{
int n;
while(scanf("%d",&n) != EOF)
{
int k = 0,count = 0;
for(int i = 2; i < sqrt(n); i++)
{
long long ans = 1;//注意相乘可能会溢出!!!
for(int j = i; ans*j <= n; j++)//读者可仔细思考为什么用ans*j而不是ans
{
ans = ans*j;
if(n%ans == 0)//每一次都判断是否能被整除
{
if(count < j-i+1)//取最长的序列
{
k = i;
count = j-i+1;
}
}
}
}
if(count == 0)//特殊情况
printf("1\n%d\n",n);
else
{
printf("%d\n",count);
count = count+k;
for(int i = k; i < count-1; i++)
{
printf("%d*",i);
}
printf("%d\n",count-1);
}
}
return 0;
}