Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Binomial coefficient in C

Here you can find the problem I'm trying to solve:

For integers n and k (0<=k<=n<1001) determine (binomial coefficient).

Input

The first line of the standard input contains one integer t (t<1001) which is the number of test cases.

In each of the next t lines there are numbers n and k.

Output

For each test print (binomial coefficient).

Example:

Input
3
0 0
7 3
1000 2
Output:
1
35
499500

I can't seem to find anything wrong in my solution (other than it's written very poorly - I've started programming quite recently):

#include <stdio.h>

int main()
{
    unsigned long int t,n,k,binomial=1;
    unsigned long int number=1;

    for(scanf("%lu",&t);t>0;t--)
    {
        scanf("%lu%lu",&n,&k);
        if(k<(n/2)) k=n-k;
        for(binomial=1,number=1;n>k;k++)
        {
            binomial=binomial*(k+1)/number;
            number++;
        }
        printf("%lu
",binomial);
    }

    return 0;

}

It works fine for the example input, but the solution is judged via a problem site

(http://www.spoj.pl/SHORTEN/problems/BINOMIAL/english/)

and the solution is not accepted. I tried other inputs too and all of them gave back the right output. My question is: Is there a reason why this solution is invalid?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As 1000C500 is around 300 digits, it cant be stored in an unsigned long. In short, you need to start over and think of a better technique.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...