Codeforces H. Ancient Wisdom

题目链接:https://codeforces.com/gym/102365/problem/H

H. Ancient Wisdom

在这里插入图片描述
David and Aram had the following conversation:

David: “Aram, you’re pretty old.”

Aram: “I’m not THAT old. If you cube your age and then multiply by C, you’d get exactly my age squared.”

Lucca overheard this conversation but isn’t sure if he caught the right value for C. Help Lucca figure out how young David could be, assuming he heard correctly.

As everyone knows, ages are positive integers.

Input
Input is a single integer, what Lucca thought he heard for the value of C (1≤C<263).

Output
Output the minimum age David could be.

Examples

Input

1029

output

21

input

10

output

10

input

1000000000000000000

output

1

Note
The average computer can do roughly 108 elementary operations in one second. If you submit a program that tries to do more than 109 operations, you shouldn’t be surprised if your program gets a Time Limit Exceeded verdict!

题目理解
输入一个整数C,使得C*Davidage3=Aramage2,Davidage,Aramage分别表示David和Aram的年龄,最后要输出最小的Davidage,其中年龄必须是正整数。

分析
题目可以抽象为cx3=a2,即求最小的x,使得cx3是一个完全平方数。进一步分析,cx3=cx*x2,其实只需要判断cx是否为一个完全平方数。再进一步分析,如果cx是一个完全平方数,那么可以得出:c=b2x,cx=(bx)2.
因此下一步就是要将c分解成一个完全平方数和一个不能开方的数的乘积或是一个完全平方数和1的乘积,其中的x就是要输出的结果。按照这个思路,可以将c分解成若干质数的乘积,也就是要找到所有的质因数,同一质因数如果出现偶数次,那么就可以构成一个完全平方数,最终是b2的一部分。
而如果一个质因数出现奇数次,这个质因数最终是组成x的一部分,而且如果质因数的次数还大于1,剩下的还可以构成完全平方数,例如:27=32*3,3组成x的一部分,32组成b2的一部分。

AC代码

#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <cstring>
#include <cstdio>
typedef long long ll;
using namespace std;
int primelist[(1<<22)];
ll len;
vector<ll>prime;

void getprime()   //构造素数表
{
    
    
	for(ll i=2;i<1<<22;i++)
	{
    
    
		if(primelist[i]==0)
		{
    
    
			prime.push_back(i);
			len++;
			for(ll j=i*i;j<1<<22;j+=i)
			{
    
    
				primelist[j]=1;
			}
		}
	}
}

int main()
{
    
    
	ll c;
	ll d=1;
	getprime();
	scanf("%lld",&c);
	for(ll i=0;i<len;i++)
	{
    
    
		int cnt=0;
		while(c%prime[i]==0)
		{
    
    
			c/=prime[i];
			cnt^=1;   //循环执行奇数次,cnt=1,执行偶数次,cnt=0
		}
		if(cnt)
			d*=prime[i];
		if(c<prime[i])
			break;
	}
	if(c!=(ll)sqrt(c)*(ll)sqrt(c)) //判断C是否为完全平方数
		d*=c;
	printf("%lld\n",d);
	
	return 0;
}

注意:

if(c!=(ll)sqrt(c)*(ll)sqrt(c)) //判断C是否为完全平方数
		d*=c;

最后这个if判断不能少,如果c是一个很大的素数或c分解后还是一个很大的素数,并且超过了素数表中最大的素数,那么这个大素数要算在结果d里面,即d=d*c;当然如果c是一个大素数的平方,通过前面的循环,c并没有消掉质因子,但可以判断出c是一个完全平方数,这时候d就不需要乘c.

思考
最后的c可不可能是一个大素数的三次方,或是一个大素数和另一个大素数的平方的乘积。其实并不会,在素数表primelist中筛选了1-222中所有的素数,如果出现这种情况,每个大素数必然大于222,结果就会大于263,所以并不会出现这种情况。其实素数表到221就可以了,取到222是保险的做法。

猜你喜欢

转载自blog.csdn.net/weixin_46155777/article/details/108906113