我应该使用哪种数据类型以C语言存储变量10 ^ 200?

时间:2014-05-11 03:54:08

标签: c biginteger largenumber

如何处理10 ^ 200或大于C语言的整数? 即使我长时间使用它也不会工作。 那我该怎么办?我听说过大整数。但不知道如何使用它。据我所知它是C#的库函数。但我正在使用C.除了大整数之外还有其他方法可以处理这么大的整数吗? 也有人可以解释我如何使用大整数?

为了澄清,我只是在寻找可以在C中使用的解决方案。

3 个答案:

答案 0 :(得分:2)

similair question

简而言之,没有内置类型,但有开源库具有此功能:{+ 3}}(Boost.Multiprecision)用于C ++,Boost license用于C语言。(LGPL v3 / v2双重许可证)

如果出于某种原因(例如许可证不兼容),您无法使用这些库,GMP如果您要自己实现此类功能,则会提供一些提示。

答案 1 :(得分:2)

这就是我们使用整数数组的方法(虽然最好使用字符数组)。我只显示了加法,休息操作,如比较,乘法减法,你可以自己编写。

#include<stdio.h>
#include<stdlib.h>
#define len 500 // max size of those numbers you are dealing

int findlength(int num[])
{
        int i=0;
        while(num[i]==0)
            ++i;
        return (len-i);


}


void equal(int num[] ,int a[])
{
        int i;

        for(i=0;i<len;++i)
            num[i]=a[i];

        free(a);

}


void print(int num[],int l)
{
        int i;

        for(i=len-l;i<len;++i)
            printf("%d",num[i]);

        printf("\n");

}


int *add(int num1[] , int num2[] )
{
        int i,carry=0;
        int *a = malloc(sizeof(int)*len); // an dynamic answer array has to be created because an local array will be deleted as soon as control leaves the function

        for(i=0;i<len;++i)
            a[i]=0;

        for(i=len-1;i>=0;--i)
        {
            a[i]=num1[i]+num2[i]+carry;
            carry=a[i]/10;
            a[i]=a[i]%10;
        }

        return a;

}


void input_number(int num[])
{
        int i=0,temp[len],j;
        char ch;

        for(i=0;i<len;++i) // fill whole array by zero. helps in finding length
            num[i]=0;

        i=0;

        printf("Enter number : ");

        while((ch=getchar())!='\n')
                temp[i++]= ch-'0'; //Saving number from left to right

        //shifting whole number to right side, now numbers are stored as 00000012 , 00000345 etc...

        for(j=0;j<=i;++j)
             num[len-1-j]=temp[i-j-1];


}

int main()
{
        int num1[len],num2[len],num3[len]; // to save space Use character array of size len.Char is also numeric type. It can hold 0- 9

        input_number(num1); // this way you can input those numbers
        input_number(num2);

        int len1=findlength(num1),len2=findlength(num2); // Might be used in Many operations.

        equal(num3,add(num1,num2));// This way define add , or subtract or any other operation you wan to do but return pointer to answer array.
        //Use equal function to equate "num3 = answer array" by some implementation.

        print(num3,findlength(num3)); // to print the number.
        // create an header file of all these function implementations and use them wherever you like

        return 0;
}

答案 2 :(得分:1)

Arbitrary-precision arithmetic的概念,并且有很多库可以满足您的要求,通常这些库正在使用整数或浮点数或Fixed-point arithmetic来处理任意精度算术。

您可以找到针对不同平台,许可证和语言的大量解决方案,这取决于您希望在什么样的环境中执行的操作,但通常您会发现很多选项。

相关问题