ACM-ICPC 2018 焦作赛区网络预赛 Give Candies(费马小定理 + 快速幂)

费马小定理 + 快速幂

 
There are N children in kindergarten. Miss Li bought them N candies. To make the process more interesting, Miss Li comes up with the rule: All the children line up according to their student number (1...N)(1...N), and each time a child is invited, Miss Li randomly gives him some candies (at least one). The process goes on until there is no candy. Miss Li wants to know how many possible different distribution results are there.

Input
The first line contains an integer T, the number of test case.The next T lines, each contains an integer N.

1≤T≤100,      1≤N≤\large 10^{100000}

Output
For each test case output the number of possible results (mod 1000000007).

样例输入
1
4
样例输出
8


题意

将N个糖果分给N个孩子,每次最少分一个糖果,知道分完为止,求一共有多少种分法。

解题思路

通过计算前几个数,很容易得出这样一个结论:当有 N 个糖果时,总的分法数为 2^{N-1}。而此题的 N 的范围达到了10^{100000},所以只能用字符串来读取这个数。

费马小定理:(a^n)%mod = (a^(n%(mod-1)))%mod    【其中mod为质数】

推导公式可得:(2^(n-1))%mod = (2^(n%(mod-1)-1))%mod     即,2^{N}模一个质数,它的结果具有周期性,周期长度为mod-1。先把N转化成模 (mod-1) 后的数,然后再计算快速幂。
 

 

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;

ll qpow(ll a, ll b)//快速幂
{
    ll ans = 1, base = a % mod;
    while (b) {
        if (b & 1)
            ans = (ans * base) % mod;
        base = (base * base) % mod;
        b >>= 1;
    }
    return ans % mod;
}

ll getnum(string s) {
    ll ans = 0, base = 1;
    ll MOD = mod - 1;
    int len = s.length();
    for (int i = len - 1; i >= 0; i--) {
        ans = (((s[i] - '0') * base) % MOD + ans % MOD) % MOD;
        base = (base * 10) % MOD;
    }
    return ans;
}

int main() {
    int T;
    cin >> T;
    string s;
    while (T--) {
        cin >> s;
        ll b = getnum(s);
        b--;
        ll ans = qpow(2, b);
        cout << ans << endl;
    }
    return 0;
}

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值