hdu2817 A sequence of numbers && hdu1420 Prepared for New Acmer(快速幂取模)
2016-04-12 09:35
501 查看
http://acm.hdu.edu.cn/showproblem.php?pid=2817
题意:给出一个数列的前三项,求这个数列的第k项。注意体重说过arithmetic or geometric sequences,只可能是等差等比数列中的一种。
首先根据前三项判断是等差还是等比,若等差则直接根据通项公式得出,等比的话数字太大,要用快速幂
快速幂取模,一种神奇的位运算算法。
例如求x的n次方,n很大时要求n次幂,而用位运算转化为二进制后,只有该位为1的才乘一次,复杂度由O(n)转化为O(logn)。至于快速幂的内部实现,其实也很简单,思想上就和dp的二进制一样,任何一个数都可以由2的幂次组成。拿本题说,x用于表示x^2^k,是每个累乘的单向且每次进行左移变化,和n的右移变化同步进行;res用于累乘合法(二进制位为1)的项,相当于幂的累加。通常快速幂都要取一下模,为了防止特别大而溢出。值得一提的是,这题连输入的数都特别大,必须都用LL。
http://acm.hdu.edu.cn/showproblem.php?pid=1420
题意:求A^B mod C
和上题想必,这题就逊色很多了
题意:给出一个数列的前三项,求这个数列的第k项。注意体重说过arithmetic or geometric sequences,只可能是等差等比数列中的一种。
首先根据前三项判断是等差还是等比,若等差则直接根据通项公式得出,等比的话数字太大,要用快速幂
快速幂取模,一种神奇的位运算算法。
例如求x的n次方,n很大时要求n次幂,而用位运算转化为二进制后,只有该位为1的才乘一次,复杂度由O(n)转化为O(logn)。至于快速幂的内部实现,其实也很简单,思想上就和dp的二进制一样,任何一个数都可以由2的幂次组成。拿本题说,x用于表示x^2^k,是每个累乘的单向且每次进行左移变化,和n的右移变化同步进行;res用于累乘合法(二进制位为1)的项,相当于幂的累加。通常快速幂都要取一下模,为了防止特别大而溢出。值得一提的是,这题连输入的数都特别大,必须都用LL。
#include <stdio.h> #include <algorithm> #include <string.h> using namespace std; typedef long long LL; const int N = 4500; const int INF = 1e8; const int mod = 200907; LL quickmod(LL x, LL n) { LL res = 1; while(n) { if(n & 1) res = (res * x) % mod; n >>= 1; x = (x * x) % mod; } return res; } int main() { // freopen("in.txt", "r", stdin); LL n, a, b, c, num, ans; scanf("%lld", &n); while(n --) { scanf("%lld%lld%lld%lld", &a, &b, &c, &num); if(a + c == b * 2) ans = (a + (num - 1) * (b - a)) % mod; else { ans = a * quickmod((b / a), (num - 1)) % mod; } printf("%d\n", ans); } return 0; }
http://acm.hdu.edu.cn/showproblem.php?pid=1420
题意:求A^B mod C
和上题想必,这题就逊色很多了
#include <stdio.h> #include <algorithm> #include <string.h> using namespace std; typedef long long LL; const int N = 4500; const int INF = 1e8; //const int mod = 200907; LL quickmod(LL x, LL n, LL mod) { LL res = 1; while(n) { if(n & 1) res = (res * x) % mod; n >>= 1; x = (x * x) % mod; } return res; } int main() { // freopen("in.txt", "r", stdin); LL n, a, b, c, ans; scanf("%lld", &n); while(n --) { scanf("%lld%lld%lld", &a, &b, &c); ans = quickmod(a, b, c); printf("%d\n", ans); } return 0; }
相关文章推荐
- 【HDU 5366】The mook jong 详解
- 【HDU 2136】Largest prime factor 详细图解
- 【HDU 1568】Fibonacci 数学公式 详解
- HDU 1568
- HDU1290
- HDU1568(Fobonacci公式)
- HDU ACM Step 2.2.2 Joseph(约瑟夫环问题)
- HDU 1405
- HDU 1297
- hdu 1205
- hdu 2087
- hdu 1016
- HDU 4898 The Revenge of the Princess’ Knight ( 2014 Multi-University Training Contest 4 )
- HDU 5592 ZYB's Premutation 线段树(查找动态区间第K大)
- HDU 5240 Exam (好水的题)
- HDU5237 Base64 大模拟
- HDU 1000
- HDU 1001
- 2015-11-11 hdu新生赛 A题(AC)
- 2015-11-11 hdu新生赛 C题(结束后一发AC)