dtoj2251. 聪明的燕姿(swallow)

题目描述

阴天傍晚车窗外

未来有一个人在等待

向左向右向前看

爱要拐几个弯才来

我遇见谁会有怎样的对白

我等的人他在多远的未来

我听见风来自地铁和人海

我排着队拿着爱的号码牌

城市中人们总是拿着号码牌,不停寻找,不断匹配,可是谁也不知道自己等的那个人是谁。可是燕姿不一样,燕姿知道自己等的人是谁,因为燕姿数学学得好!燕姿发现了一个神奇的算法:假设自己的号码牌上写着数字S,那么自己等的人手上的号码牌数字的所有正约数之和必定等于S。

所以燕姿总是拿着号码牌在地铁和人海找数字(喂!这样真的靠谱吗)可是她忙着唱《绿光》,想拜托你写一个程序能够快速地找到所有自己等的人。


Sol.
题意:求所有正约数之和=S的数。S<=2e9
这种题好像没啥好办法,那就尝试把它搜出来。
对于S,我们分解为S=(1+p1+p1^2+..p1^a1)*(1+p2+p2^2+..p2^a2)...
我们从大到小枚举S的因数p(p<sqrt(S)),对于每个因数枚举次数,。
当然如果p>sqrt(n),那么p的最高次为1,我们考虑搜到最后了再判掉它。
效率我也不会分析....
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#define ll long long
using namespace std;
int T,n,tot,flag[10000005],cnt,t; 
ll S,ans[10000005],pri[10000005];
bool check(ll x){
    if(x<n)return !flag[x];
    int o=sqrt(x);
    for(int i=2;i<=o;i++)if(x%i==0)return 0;
    return 1;
}
void dfs(ll ns,int k,ll now){
    if(ns==1){ans[++cnt]=now;return;}
    if(k==0) {
        if(check(ns-1)&&ns>pri[t])ans[++cnt]=1LL*now*(ns-1);
        return;
    }
    for(ll x=pri[k];;x=x*pri[k]){
        ll tmp=(x-1)/(pri[k]-1);
        if(ns%tmp==0)dfs(ns/tmp,k-1,now*x/pri[k]);
        if(tmp>ns)break;
    }
}
void work(){
    t=1;for(;1LL*pri[t]*pri[t]<=S;t++);
    cnt=0;dfs(S,t,1);
    sort(ans+1,ans+cnt+1);
    cnt=unique(ans+1,ans+cnt+1)-ans-1;
    printf("%d
",cnt);
    for(int i=1;i<=cnt;i++)printf("%lld%c",ans[i],i==cnt?'
':' ');
}
int main(){
    n=10000000;
    flag[0]=flag[1]=1;
    for(int i=2;i<=n;i++){
        if(!flag[i]){pri[++tot]=i;}
        for(int j=1;j<=tot&&i*pri[j]<=n;j++){
            flag[i*pri[j]]=1;
            if(i%pri[j]==0)break;
        }
    }
    while(~scanf("%lld",&S))work();
    return 0;
}
View Code
 
 
原文地址:https://www.cnblogs.com/liankewei/p/12300316.html