We say that x is a perfect square if, for some integer b, x = b2. Similarly, x is a perfect cube if, for some integer b, x = b3. More generally, x is a perfect pth power if, for some integer b, x = bp. Given an integer x you are to determine the largest p such that x is a perfect pth power.
Input
Each test case is given by a line of input containing x. The value of x will have magnitude at least 2 and be within the range of a (32-bit) int in C, C++, and Java. A line containing 0 follows the last test case.
Output
For each test case, output a line giving the largest integer p such that x is a perfect p
th power.
Sample Input 1 | Sample Output 1 |
---|---|
17 1073741824 25 0 | 1 30 2 |
题目的大概意思是——给出一个n,n=b^p,求出最大p值。(b未知)
思路:
首先利用唯一分解定理,把n写成若干个素数相乘的形式。接下来对于每个素数的指数求最大公约数,该公约数就是所能到达的最大p值。
有一点要注意的是如果n为负数的话,如果当前p值为偶数,就一直除2直到p为奇数。(被坑了。)
//Asimple #include <bits/stdc++.h> #define INF (1<<20) #define mod 10007 #define swap(a,b,t) t = a, a = b, b = t #define CLS(a, v) memset(a, v, sizeof(a)) #define debug(a) cout << #a << " = " << a <<endl using namespace std; typedef long long ll; const int maxn = 70000; const double PI=atan(1.0)*4;int n, m, num, res, ans, len, T, k;int a[maxn]; int pr[maxn]; int gcd(int a, int b) { return b==0?a:gcd(b, a%b); } void solve() { CLS(a, 0); len = 0; for(int i=2; i*i<=maxn; i++) { if( !a[i] ) { pr[len++] = i; for(int j=i; j<maxn; j+=i) a[j] = 1; } } } void input() { solve(); while( cin >> n && n ) { ans = 0; int f = 0; if( n < 0 ) { n = -n; f = 1; } for(int i=0; i<len && n>1; i++) { if( n%pr[i]==0 ) { res = 0; while( n%pr[i]==0 ) { res ++; n /=pr[i]; } ans = gcd(ans, res); } } if( n>1 ) ans = 1; if( f ) while( ans%2==0 ) ans/=2; cout << ans << endl; } } int main(){ input(); return 0; }