天天看點

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

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

México and Central America 2004

對于式子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;
}
           

繼續閱讀