大数的因子

时间:2014-12-28 06:57:37

标签: c

如何计算像300这样的数字因子,因为输出甚至不在无符号long long int的范围内?请帮忙。

#include<stdio.h>
#include<stdlib.h>


unsigned long long int factorial(int number) {
    unsigned long long int temp;

    if(number <= 1) return 1;

    temp = (number * factorial(number - 1));
    return temp;
}

int main(){
    int t,k,i,a[100001];
    unsigned long long int sum[100001];
    scanf("%d",&t);
    for(i=0;i<t;i++){
       scanf("%d",&a[i]);

    }
    for(k=0;k<t;k++){
             sum[k]=0;
    for(i=0;i<=a[k];i++){
        sum[k] += ((factorial(a[k])/(factorial(i)*factorial(a[k]-i)))%3);
         //printf("%d\n",sum[k]);
    }}
    for(i=0;i<t;i++){
        printf("%llu\n",sum[i]);
    }
    return 0;

}

我试过这个,但它只停在60岁!

1 个答案:

答案 0 :(得分:1)

您可以针对Factorials of large numbers尝试此操作:

#include<iostream>
#include<cstring>

int max = 5000;

void display(int arr[]){
    int ctr = 0;
    for (int i=0; i<max; i++){
        if (!ctr && arr[i])         ctr = 1;
        if(ctr)
            std::cout<<arr[i];
    }
}


void factorial(int arr[], int n){
    if (!n) return;
    int carry = 0;
    for (int i=max-1; i>=0; --i){
        arr[i] = (arr[i] * n) + carry;
        carry = arr[i]/10;
        arr[i] %= 10;
    }
    factorial(arr,n-1);
}

int main(){
    int *arr = new int[max];
    std::memset(arr,0,max*sizeof(int));
    arr[max-1] = 1;
    int num;
    std::cout<<"Enter the number: ";
    std::cin>>num;
    std::cout<<"factorial of "<<num<<"is :\n";
    factorial(arr,num);
    display(arr);
    delete[] arr;
    return 0;
}