UVA 11752 The Super Powers(至少是两个正整数的幂的幂数)

来源:互联网 发布:啊哈算法 在线阅读 编辑:程序博客网 时间:2024/06/06 01:06

题目链接:
UVA 11752 The Super Powers
题意:
求出1~2^64 - 1范围内的所有幂数,并且每个幂数至少是两个正整数的幂。
分析:
要用unsigned long long。
对于任意正整数x它的指数k只要k不是素数,那么x^k必然可以表示成两个不同的正整数的幂。例如512 = 2^9 = (2^3)^3 = 8 ^3
需要知道底数和指数的范围,然后判断指数是不是素数,如果不是素数那就快速幂把结果保存下来。显然底数需要小于1<<16,因为底数至少需要4次方可以,而数据的最大值小于1<<64.对于底数i假设其指数上限为limit则i^limit <= 2^64 - 1,取log得:limit * log(i) < log(2 ^ 64 - 1),所以Limit < log(2 ^ 64 - 1) / log(i),
用上<climits>头文件,2 ^ 64 - 1 = ULONG_LONG_MAX;

#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <climits>#include <cmath>#include <ctime>#include <cassert>#include <bitset>#define IOS ios_base::sync_with_stdio(0); cin.tie(0);using namespace std;typedef long long ll;typedef unsigned long long ull;const int MAX_N = 1000010;const ull INF = ULONG_LONG_MAX;int cnt = 0;ull ans[MAX_N];bitset<MAX_N> bs;void GetPrime(){    bs.set();    for(int i = 2; i < MAX_N; i++){        for(int j = 2 * i; j < MAX_N; j += i){            bs[j] = 0;        }    }}ull quick_pow(ull n, ull m){    ll res = 1, tmp = n;    while(m){        if( m & 1) res = res * tmp;        tmp = tmp * tmp;        m >>= 1;    }    return res;}int main(){    GetPrime();    ans[cnt++] = 1;    int len = (1 << 16);    double Max = log(1.0 * INF);    for(int i = 2; i < len; i++){        int limit = (int)ceil(Max / log(i * 1.0));        for(int j = 4; j < limit; j++){            if(bs[j] == 0) ans[cnt++] = quick_pow(i, j);        }    }    sort(ans, ans + cnt);    int total = unique(ans, ans + cnt) - ans;    for(int i = 0; i < total; i++){        printf("%llu\n", ans[i]);    }    //printf("cnt = %d\n", cnt);    return 0;}
0 0