【问题标题】:which datatype should i use to store a variable 10^200 in C language?我应该使用哪种数据类型在 C 语言中存储变量 10^200?
【发布时间】:2014-06-28 14:47:45
【问题描述】:
如何处理 10^200 或大于 C 语言的整数?
即使我使用 long long 也不起作用。
那我该怎么办?我听说过大整数。但不知道如何使用它。据我所知,它是 C# 的库函数。但我正在使用 C。除了大整数之外,还有其他方法可以处理这么大的整数吗?
有人能解释一下如何使用大整数吗?
为了澄清,我只是在寻找一个可以在 C 中工作的解决方案。
【问题讨论】:
标签:
c
biginteger
largenumber
【解决方案3】:
这就是我们使用整数数组的方式(尽管使用字符数组更好)。我只展示了加法,比较之类的其余操作,乘法减法您可以自己编写。
#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;
}