1. 程式人生 > >Consecutive Factors (20)

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 356*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.

輸入描述:
Each input file contains one test case, which gives the integer N (131).

輸出描述:
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.

輸入例子:
630

輸出例子:
3
567

思路:
這道題挺有意思,最先我是想要將找到所有因素然後維護最大,後面發現想錯了,因為輸出並沒有讓我們求完所有因素,這道題只需要找到最大連續因素。數n的大小是int,大概在12!以內,又因為我們列舉時其實到sqrt(n)就可以了,所以時間複雜度大致在11*sqrt(n),直接暴力維護最大值就可以了

#include <iostream>
#include <cmath>
using namespace std;
int main(){
    long long n;
    cin>>n;
    long long sqr=(long long)sqrt(1.0*n);
    long long first=0,len=0;               //len為最長連續整數的長度,first是其中第一個
    for(long long i=2;i<=sqr;i++){         //遍歷第一個整數
        long long temp=1,j;                //temp為當前連續整數的乘積
        for(j=i;;j++){
            temp*=j;
            if(n%temp!=0) break;           //j不斷加1直到temp不能整除n
        }
        if(j-i>len){                       //更新最長長度與第一個整數
            len=j-i;
            first=i;
        }
    }
    if(len==0) cout<<1<<endl<<n;          //根號n範圍內都無解,只能輸出n本身(素數)
    else{
        cout<<len<<endl;
        for(long long i=0;i<len;i++){
            cout<<first+i;
            if(i<len-1) cout<<"*";
        }
    }
    return 0;
}