1096 Consecutive Factors (20分)

1 题目

1096 Consecutive Factors (20分)
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<231).

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 factor[1]factor[2]…*factor[k], where the factors are listed in increasing order, and 1 is NOT included.

Sample Input:
630
    
Sample Output:
3
5*6*7

2 解析

2.1 题意

求整数的n最长连续整数乘积的个数与这段的最长连续整数乘积

2.2 思路

  • 因为数据长度为231,因此需要用long long来存储;

步骤:

  • 1 因为n不能被除自己外的大于 n \sqrt{n} n 的数整除,因此只需要从2~ n \sqrt{n} n 开始遍历连续整数的第一个,求此时的n最多能被多少个连续整数的乘积整除,并不断更新最长的连续整除的乘积的个数ansLen(初始长度为0)和记录连续整数的其实位置ansI;
  • 2 如果遍历结束,ansLen还是0,则不超过 n \sqrt{n} n 的整数中不存在能整除N的连续整数,输出n本身;如果ansLen不为,则输出[ansI,ansI + ansL]区间内的整数。

3 参考代码

#include <cstdio>
#include <cmath>
typedef long long ll;


int main(int argc, char const *argv[])
{
    ll n;
    ll ansLen = 0;
    ll ansI = 0;

    scanf("%lld", &n);
    ll sqr = (ll)sqrt(1.0*n);
    for (ll i = 2; i <= sqr; ++i)//连续遍历第一个整数
    {
        ll templen = 0;//临时的连续乘积长度
        ll tempI = i;//临时的整数i
        ll temp = i;//连续整数的乘积
        while(n % temp == 0){//让tempI从i不断加1,看最长能达到多长
            templen++;//更新连续乘积长度
            tempI++;//下一个整数
            temp *= tempI;//更新连续整数
        }

        if(templen > ansLen){//如果当前数的连续乘积个数更大,则更新
            ansLen = templen;
            ansI = i;
        }
//        ll tempI = i;
//        ll temp = 1;
//        while (1){//让tempI从i不断加1,看最长能达到多长
//            temp *= tempI;//当前连续整数的乘积
//            if(n % temp != 0) break;//如果不能整除n,结束计算
//            if(tempI - i + 1 > ansLen){//发现更长长度
//                ansLen = tempI - i + 1;
//                ansI = i;
//            }
//            tempI++;//下一个整数
//        }
    }

    if(ansLen == 0){//如果长度为0,说明根号n范围内无解,输出n本身
        printf("1\n%lld",n);
    }else{
        printf("%lld\n", ansLen);
        for (ll i = 0; i <  ansLen; ++i)
        {
            if(i != 0) printf("*");
            printf("%lld", ansI + i);
        }
    }
    return 0;
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页