C中最大的数字

时间:2013-06-11 06:36:00

标签: c

scanf("%d",&a);
for(b=1;b<=a;++b)
{
    c*=b;
}
printf("%lu",c);

我想得到100的答案! 阶乘100。 我怎么能得到这个? (我想获得更大范围的数字) 我们有无限的数量限制吗?

4 个答案:

答案 0 :(得分:23)

最大整数范围几乎在每个(现代)平台上2^31 - 1(尽管按照标准,int只需要至少16位)。对于您的指定平台,它将在INT_MAX中定义为<limits.h>

100!显然会远远超过这个。要计算C中这么大的内容,您需要一个大整数库,例如GMP

正如警示一样,如果您决定尝试使用double(可以容纳此数量的数字),由于精度损失,您将得到错误的答案。这很容易发现 - 在我的机器上,最后的数字是48,这显然是无意义的:100!必须可以被100整除,因此必须有00作为最后两位数。

答案 1 :(得分:4)

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#if __STDC_VERSION__>=199901L
#include <inttypes.h>
#else
#define PRIu16 "hu"
#endif

typedef struct _unums {
    size_t size;
    uint16_t *nums;//array 
} UNums;

void UNums_init(UNums *num, uint16_t n){
    num->nums = (uint16_t*)malloc(sizeof(uint16_t));
    num->nums[0] = n;
    num->size = 1;
}

void UNums_mul(UNums *num, uint16_t n){
    uint16_t carry = 0;
    size_t i;

    for(i=0;i<num->size;++i){
        uint32_t wk = n;
        wk = wk * num->nums[i] + carry;
        num->nums[i] = wk % 10000;
        carry = wk / 10000;
    }
    if(carry){
        num->size += 1;
        num->nums = (uint16_t*)realloc(num->nums, num->size * sizeof(uint16_t));
        num->nums[i] = carry;
    }
}

void UNums_print(UNums *num){
    size_t i = num->size;
    int w = 0;
    do{
        --i;
        printf("%0*" PRIu16, w, num->nums[i]);
        if(!w) w = 4;
    }while(i!=0);
}

void UNum_drop(UNums *num){
    free(num->nums);
    num->nums = NULL;
}

int main( void ){
    UNums n;
    uint16_t i;

    UNums_init(&n, 1);
    for(i=2;i<=100;++i)
        UNums_mul(&n, i);
    UNums_print(&n);//100!
    UNum_drop(&n);
    return 0;
}

答案 2 :(得分:1)

对于较小的数字,最好使用unsigned long long而不是int。但是你仍然限制了a可以使用的最大数字。您可以尝试doublefloat,但您可能会遇到进动错误。

答案 3 :(得分:1)

您可以使用GMP library

安装:

sudo apt-get install libgmp3-dev

main.c:

#include <gmp.h>

void f() tooBigForYourShell {
    mpz_t n;                     // declare a big n number
    mpz_init_set_ui(n,0);        // assign 0 as starting value
    mpz_setbit(n, 1UL << 24);    // set bit 2^24 (index 2^24 and not 24...) as 1.
    gmp_printf("%Zd\n", n);      // display the result
}

int main() {
    tooBigForYourShell();
    return 0;
}

编译:

gcc main.c -lgmp && ./a.out
???
profit, enjoy your 2^(2^24) number on stdout.

enter image description here 注意:前面还有更多数字......

您可以 theoretically 使用最多 37 位(所以 2^38 - 1 ?),但要小心,因为它会占用您的大量 CPU。

/!\ 如果您使用 2^(2^37),我对任何损坏概不负责。