Perfect Squares 费马小定理求乘法逆元k=b^(p-2)

Problem Description
A number x is called a perfect square if there exists an integer b
satisfying x=b^2. There are many beautiful theorems about perfect squares in mathematics. Among which, Pythagoras Theorem is the most famous. It says that if the length of three sides of a right triangle is a, b and c respectively(a < b In this problem, we also propose an interesting question about perfect squares. For a given n, we want you to calculate the number of different perfect squares mod 2^n. We call such number f(n) for brevity. For example, when n=2, the sequence of {i^2 mod 2^n} is 0, 1, 0, 1, 0……, so f(2)=2. Since f(n) may be quite large, you only need to output f(n) mod 10007.


Input
The first line contains a number T<=200, which indicates the number of test case.
Then it follows T lines, each line is a positive number n(0

Output
For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is f(x).


Sample Input
2
1
2


Sample Output
Case #1: 2
Case #2: 2


告诉一个数字n,求完全平方数摸2^n有多少不同的结果。打表会得到一个循环的结果,总结n分奇数偶数时的规律。
n为奇数 2+(4^n/2-1)/3

n为偶数 2+2/3*(4^(n/2-1)-1)

求2^n时要用快速幂

算除法时分子很大,所以要用到逆元,利用费马小定理求逆元;

费马小定理: b(p-1)≡1(mod p),即:假如b是整数,p是质数,且b,p互质(即两者只有一个公约数1),那么b的(p-1)次方除以p的余数恒等于1。

b*k≡1(mod p)//k为b关于p的逆元;

b(p-1)≡1(mod p)

得k=b^(p-2)(mod p)


代码如下:

#include
#include
using namespace std;
typedef long long ll;
const int p=10007;

ll pow(ll x,ll n)
//快速幂
{
    ll b=1;
    while(n)
    {
        if(n&1) b=b*x%p;
        x=x*x%p;
        n>>=1;
    }
    return b;
}


int main()
{
    int t;
    ll k=pow(3,p-2);
//3关于p的逆元
    scanf("%d",&t);
    for(int i=1;i<=t;i++)
    {
        ll n,a;
        scanf("%lld",&n);
        if(n&1)
        {
            ll a=(pow(4,n/2)-1)%p;
            n=(2+(a*k)%p)%p;
        }
        else
        {
            ll a=(pow(4,n/2-1)-1)%p;
            n=(2+(2*a*k)%p)%p;
        }
        printf("Case #%d: %lld\n",i,n);
    }
    return 0;
}


你可能感兴趣的:(数论)