1096 Consecutive Factors (20 分)

题意

给出一个正整数N,求一段连续的整数,使得N能被这段连续整数的乘积整除。如果有多个方案,输出连续整数个数最多的方案;如果还有多种方案,输出其中第一个数最小的方案。

思路

  1. 首先需要注意到的一点是,N不会被除自己以外的大于(sqrt{N})的整数整除,因此只需要从2 ~ N遍历连续整数的第一个,求此时N能被最多多少个连续整数的乘积整除。在此过程中,如果有发现长度比当前的最长长度ansLen更长的情况(ansLen初始化为0),就更新ansLen和对应的第一个整数ansl.
  2. 如果遍历结束后ansLen依然为0,那么说明不超过JN的整数中不存在能整除N的连续整数,因此答案就是N本身;否则,输出[ansl, ansl + ansLen)区间内的整数。
int n;

int main()
{
    cin>>n;

    int ansl=0,anslen=0;
    for(int i=2;i<=n/i;i++)
        if(n % i == 0)
        {
            int l=i,r=i;
            int m=n;
            while(m % r == 0)
            {
                if(r-l+1 > anslen)
                {
                    ansl=l;
                    anslen=r-l+1;
                }
                m/=r;
                r++;
            }
        }

    if(anslen == 0) cout<<1<<endl<<n<<endl;
    else
    {
        cout<<anslen<<endl;
        for(int i=0;i<anslen;i++)
            if(i == 0) cout<<i+ansl;
            else cout<<'*'<<i+ansl;
        cout<<endl;
    }

    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/fxh0707/p/14427679.html