【ZOJ - 2116】Christopher's Christmas Letter(Lucas)

Dashing thro’ the snow,
In a one-horse open sleigh,
O’er the fields we go,
Laughing all the way;
Bells on bobtail ring,
Making spirits bright;
What fun it is to ride and sing
A sleighing song tonight!
Jingle, bells! Jingle, bells!
Jingle all the way!
Oh! What fun it is to ride in a one-horse open sleigh!

The Christmas Eve last year becomes a story that filled Christopher’s hearts with joy. With your help on “Souvenirs of Love” problem, Christopher has already been out of danger. (If you’re interested in the background, please see Christopher’s Key Ring)

This time, Christopher received a letter from Father Christmas. It was sent on Christmas Eve, but coz the mailing jam, it was just received. To his surprise, Father Christmas didn’t fall asleep as well as Christopher (but different reason ;). What is Santa Claus’s trouble? Let’s see, it’s a math problem:

There’re N different XX toys, to be sent to city X. Each time Santa Claus will send M (0 <= M <= N) toys to a single person as presents. The number of ways for fixed M is well-known I think. It is very strange that the people in city X hate such number M for a fixed N, if and only if the number of ways for it is multiple of a fixed prime P.

Santa Claus wonders how many Ms will be satisfying (not be hated by people in city X).

Input

The first line of the input contains one integer X (1 <= X <= 500), which is the number of test cases.

Next X lines each contains two integers N (1 <= N <= 10^100) and P (a prime, 2 <= P <= 10^7).

Output

You should write exactly X lines to the output. Each line contains the total number of satisfying Ms for that test case.

Sample Input

2
6 7
6 2

Sample Output

0
3

(adviser)
Site: http://zhuzeyuan.hp.infoseek.co.jp/index.files/our_contest_20040619.htm

问题问得就是m在0到n有多少个m使得 Cmn% p0 C n m %   p ≡ 0

这个只要一些Luas定理一个性质。
我们把n和m都按p进制表示:

n=n0+n1p+n2p2+...+nkpkm=m0+m1p+m2p2+...+mkpk n = n 0 + n 1 p + n 2 p 2 + . . . + n k p k m = m 0 + m 1 p + m 2 p 2 + . . . + m k p k

那么
Cmn% pi=0kCmini% p C n m %   p ≡ ∏ i = 0 k C n i m i %   p

若存在任意一项 ni<mi n i < m i ,则这个组合数与0同余。
所以我们可以反过来看使得这个组合数不为0的时候m的情况,那么就是 ki=0(ni+1) ∏ i = 0 k ( n i + 1 )
答案就是n+1减掉这个不合法的。

java大数写的爽啊。
代码:

import java.math.BigInteger;
import java.util.Scanner;

public class Main 
{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while((t--)>0)
        {
            BigInteger n=sc.nextBigInteger();
            BigInteger p=sc.nextBigInteger();
            int cnt=0;
            BigInteger ans=n;
            BigInteger temp=BigInteger.ONE;
            while(!n.equals(BigInteger.ZERO))
            {
                temp=temp.multiply(n.mod(p).add(BigInteger.ONE));
                n=n.divide(p);
            }
            System.out.println(ans.subtract(temp).add(BigInteger.ONE));
        }
    }

}

你可能感兴趣的:(Lucas定理,组合数学)