POJ 2109 Power of Cryptography(我的水题之路——k^n=p)

时间:2022-05-02 18:23:46
Power of Cryptography
Time Limit: 1000MS   Memory Limit: 30000K
Total Submissions: 12137   Accepted: 6206

Description

Current work in cryptography involves (among other things) large prime numbers and computing powers of numbers among these primes. Work in this area has resulted in the practical use of results from number theory and other branches of mathematics once considered to be only of theoretical interest. 
This problem involves the efficient computation of integer roots of numbers. 
Given an integer n>=1 and an integer p>= 1 you have to write a program that determines the n th positive root of p. In this problem, given such integers n and p, p will always be of the form k to the n th. power, for an integer k (this integer is what your program must find).

Input

The input consists of a sequence of integer pairs n and p with each integer on a line by itself. For all such pairs 1<=n<= 200, 1<=p<10 101 and there exists an integer k, 1<=k<=10 9 such that k n = p.

Output

For each integer pair n and p the value k should be printed, i.e., the number k such that k n =p.

Sample Input

2 16
3 27
7 4357186184021382204544

Sample Output

4
3
1234

Source


对于式子k^n=p,题中给出n和p,求k。

这道题拿到一开始想到的是math里的一个函数pow(m, n),即是可以求m^n的值。之前有用过他来开方,所以就想到了,加上看到discuss里的提示,就直接用了pow(m, 1 / n)求值,不过很奇怪的是WA了很多次,完全找不到原因,去搜索了几个人的AC代码,粘贴过去,貌似也没有办法一直WA。比较怀疑是POJ的管理员把数据改强大了。之后就没有办法用了二分法求值。

代码(二分法 1AC):
#include <cstdio>
#include <cstdlib>
#include <cmath>

int main(void){
    double n, m;
    long long left, right, mid;

    while(scanf("%lf%lf",&n,&m)!=EOF){
        left = 0;
        right = 1000000002;
        while (right - 0.00000001 > left){
            mid = (left + right) / 2;
            if (pow(mid, n) - m > 0){
                right = mid;
            }
            else if (pow(mid, n) - m < 0){
                left = mid;
            }
            else{
                printf("%.0lld\n", mid);
                break;
            }
        }
    }
    return 0;
}

也贴一下用pow函数的代码,挺帅的就是不能AC。(1CE 4WA):
#include<stdio.h>
#include<math.h>

int main()
{
    double n, m;
    while(scanf("%lf%lf", &n, &m) != EOF)
        printf("%.0lf\n" ,pow(m, 1 / n));
    return 0;
}