首页 > 代码库 > UVA 113-Power of Cryptography(二分+double处理大数据)
UVA 113-Power of Cryptography(二分+double处理大数据)
Description
Power of Cryptography
Power of Cryptography |
Background
Current work in cryptography involves (among other things) large prime numbers and computing powers of numbers modulo functions of 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 of only theoretical interest.
This problem involves the efficient computation of integer roots of numbers.
The Problem
Given an integer and an integer you are to write a program that determines , the positive root of p. In this problem, given such integers n and p, p will always be of the form for an integer k (this integer is what your program must find).
The 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 , and there exists an integer k, such that .
The Output
For each integer pair n and p the value should be printed, i.e., the number k such that .
Sample Input
2 16 3 27 7 4357186184021382204544
Sample Output
4 3 1234
题意:给出你n,p,n的k次方等于p,让你求k
思路:首先得了解acm中常用的极限值
int和long都是用32位来存储最大值和最小值分别为2147483647(109), -2147483648;
long long 是用64位来存储最大值和最小值分别为9223372036854775807(1018),-9223372036854775808;
float的最大值和最小值分别为3.40282e+038(1038),1.17549e-038(10-38);
double的最大值和最小值分别为1.79769e+308(10308),2.22507e-308(10-308)
题目给出的n在10^108,所以用double
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int main() { double k,p,n; while(~scanf("%lf %lf",&n,&p)) { int low,high,mid; low=1; high=pow(10,9); while(low<=high) { mid=(low+high)/2; k=pow(mid,n); if(k==p) { printf("%d\n",mid); break; } else if(k<p) low=mid+1; else high=mid-1; } } return 0; }
看到网上大牛们的做法,感觉很神奇,特此膜拜
题意:给出n和p,求出 ,但是p可以很大()
如何存储p?不用大数可不可以?
先看看double行不行:指数范围在-307~308之间(以10为基数),有效数字为15位。
误差分析:
令f(p)=p^(1/n),Δ=f(p+Δp)-f(p)
则由泰勒公式得
(Δp的上界是因为double的精度最多是15位,n有下界是因为 )
由上式知,当Δp最大,n最小的时候误差最大。
根据题目中的范围,带入误差公式得Δ<9.0e-7,说明double完全够用(这从一方面说明有效数字15位还是比较足的(相对于float),这也是float用的很少的原因)
这样就满足题目要求,所以可以用double过这一题。
#include<stdio.h> #include<math.h> int main() { double a, b; while(scanf("%lf%lf",&a,&b) != EOF) printf("%.0lf\n",pow(b,1/a)) return 0; }
UVA 113-Power of Cryptography(二分+double处理大数据)