您的位置:首页 > 其它

project euler 29 Distinct powers

2018-01-10 15:11 381 查看

题目:

https://projecteuler.net/problem=29

题意:

Consider all integer combinations of ab for 2≤a≤5 and 2≤b≤5:

22=4,23=8,24=16,25=32

32=9,33=27,34=81,35=243

42=16,43=64,44=256,45=1024

52=25,53=125,54=625,55=3125

If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:

4,8,9,16,25,27,32,64,81,125,243,256,625,1024,3125

How many distinct terms are in the sequence generated by ab for 2≤a≤100 and 2≤b≤100?

给出a,b的范围,2≤a≤100,2≤b≤100,求ab所有的运算结果中有多少个不同的数字。例如2≤a≤5,2≤b≤5,答案是15

思路:

用C++写大整数不好搞,把所有的a分解质因子,a的质因子不超过100,用一个vector储存记录a的每个质因子的个数。例如vec[i]=2,代表a中有2个质因子i。求ab时,把相应的质因子个数扩大b倍,就是ab的质因子表示形式,然后用set去重即可。

:在去重这个问题上,为提高效率,我尝试了BKDRhash,但是seed值取的较小时(如31,131,1313),得出的答案是不对的,较大时正确。

代码:

#include <bits/stdc++.h>
using namespace std;

const int N = 100 + 10;

vector<int> vec
;

void preprocess(int n)
{
for(int i = 2; i <= n; ++i)
{
vec[i].resize(n+1, 0);
int val = i;
for(int j = 2; j <= val; ++j)
{
while(val % j == 0)
{
++vec[i][j];
val /= j;
}
}
}
}
int main()
{
int n = 100;
preprocess(n);
set<vector<int>> ste;
vector<int> temp(n+1, 0);
for(int i = 2; i <= n; ++i)
{
for(int j = 2; j <= n; ++j)
{
for(int k = 2; k <= n; ++k)
temp[k] = vec[i][k] * j;
ste.emplace(temp);
}
}
printf("%d\n", ste.size());
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: