如何增加C中的整数范围?

时间:2015-01-03 09:26:27

标签: c

我试图在SPOJ上解决Small Factorial问题并得到错误的回答'。我写了以下代码:

#include <stdio.h>

int main() {

int t,i, num;
unsigned long long int fact=1;

scanf ("%d", &t);

while (t-- >0) {

    fact=1;

    scanf ("%d", &num);

    for (i=num; i>0; i--) {
        fact*=i;
    }
    printf ("%llu\n",fact);
}

return 0;
}

此代码未找到像100这样的大输入的因子。需要进行哪些更改?

1 个答案:

答案 0 :(得分:0)

在C和C ++中,您的最大允许范围是-2 ^ 63 + 1到+ 2 ^ 63-1,这是long long数据类型。如您所见,此范围仍然太小,无法存储> 20位数。 您必须使用char数组来存储每个数组索引的单个数字。 一种在C ++中执行此操作的方法:

#include<stdio.h>
#include<iostream>
int main()
{
    int t;
    char a[200]; //array will have the capacity to store 200 digits.
    int n,i,j,temp,m,x;

    scanf("%d",&t); //enter total elements
    while(t--)
    {
       scanf("%d",&n); // enter no. one at a time
       a[0]=1;  //initializes array with only 1 digit, the digit 1.
       m=1;    // initializes digit counter

       temp = 0; //Initializes carry variable to 0.
       for(i=1;i<=n;i++)
       {    
            for(j=0;j<m;j++)
            {

               x = a[j]*i+temp; //x contains the digit by digit product
               a[j]=x%10; //Contains the digit to store at position j
               temp = x/10; //Contains the carry value that will be stored on later indeces
            }
             while(temp>0) //while loop that will store the carry value on array.
             {
               a[m]=temp%10;
               temp = temp/10;
               m++; // increments digit counter
             }
      }
              for(i=m-1;i>=0;i--) 
              printf("%d",a[i]);
              printf("\n");
    }
    return 0;
}
相关问题