Description
一个正整数N的因子中可能存在若干连续的数字。
例如,630可以分解为3*5*6*7,其中5、6、7就是3个连续的数字。
给定任一正整数N,要求编写程序求出最长连续因子的个数,并输出最小的连续因子序列。
Input
一个大于1的正整数N(1 < N < 2^{31}1<N<231)。
Output
再第一行中输出最长连续因子的个数;
然后在第二行中按“因子1*因子2*……*因子k”的格式输出最小的连续因子序列,其中因子按递增顺序输出,1不算在内。
中间用1个空格隔开。
Sample Input 1
630
Sample Output 1
3 5*6*7
我的代码:
#include <stdio.h>
#include<math.h>
#include<string.h>
int main()
{
int n,x=1,first=0,count=0,max=0,sum=0;
scanf("%d", &n);
for (int i = 2; i <= sqrt(n)+1; i++)//只需要执行根号次数+1次就可以
{
count = 0;//连续因子的个数
x = 1;//累乘起来
for (int k = i; k <= n; k++)
{
x *= k;
count++;
if (n % x!=0)//如果累乘大于了n,就把最长的连续因子存起来
{
if (count-1 > max)
{
first = i;//记录第一个连续因子
sum = x;
max = count - 1;
}
break;
}
}
}
int flag = 0;
if (max == 0)//如果是质数的话
{
printf("1\n%d", n);
}
else printf("%d\n", max);
for (int i = first; i < first + max; i++)
{
if (flag++)putchar('*');
printf("%d", i);
}
return 0;
}
别人的代码:
#include <stdio.h>
#include <math.h>
int main()
{
int n,i,j,count=0,first=0,maxn,temp;
scanf("%d",&n);
maxn=sqrt(n)+1;
for(i=2; i<=maxn; i++)
{
temp=1;
for(j=i; j<=maxn; j++)
{
temp*=j;//连乘积
if(n%temp!=0)//加入一个因子后变成非连乘积
break;
}
if(j-i > count)
{
count=j-i;//记录连乘积的最大因子个数
first=i;//连成积的第一个因子
}
}
if(first==0)//1和质数
printf("%d\n%d",1,n);
else
{
printf("%d\n",count);
for(i=0; i<count; i++,first++)
i==0?printf("%d",first):printf("*%d",first);
}
return 0;
}
我一开始为了6这个测试点恼火了很久,调试了很久才发现2*3=6之后不会再多一次循环了,看了别人的代码发现思维还是有差距,用 j - i 包含了直接整除break的情况和整除不break的情况,还是得多看多写才行。