如何在变量(i)中存储大量数字并且不需要更改程序的大部分内容? 是否有可用的数据类型来存储例如100的因子?
#include<stdio.h>
#include<conio.h>
void main()
{
long long int i = 1;
long long int sum = 0;
long long int j = 0;
long long int digit = 0;
for(j = 500; j >= 1; j--)
{
i = i * j;
}
printf("%lld", i);
while(i > 0)
{
digit = i%10;
i = i/10;
sum = sum + digit;
}
printf("\n%lld", sum);
getch();
}
答案 0 :(得分:1)
对于如此大的数字,没有内置语言支持。您有两种选择:
如果您决定采用第二条路径,您可能需要考虑在数组中存储数字(不一定是十进制),并使用众所周知的学校算法执行算术运算。请记住,与大量优化的库代码相比,它(可能相当大)效率低。
答案 1 :(得分:1)
@MarcinŁoś在没有使用库或滚动自己的功能的情况下没有C解决方案。
Follows是一个有趣但不富有想象力的解决方案,其中大数字存储为char
的数组(以相反的顺序)。
#include <stdio.h>
#include <string.h>
#include <math.h>
void Mult(char *BigNum, unsigned Factor) {
unsigned Accumulator = 0;
char Digit;
while ((Digit = *BigNum) != '\0') {
Accumulator += ((unsigned)(Digit - '0')) * Factor;
*BigNum++ = Accumulator%10 + '0';
Accumulator /= 10;
}
while (Accumulator > 0) {
*BigNum++ = Accumulator%10 + '0';
Accumulator /= 10;
}
*BigNum = '\0';
}
int main(){
unsigned N = 500;
unsigned Factor;
char BigNum[(size_t) (N*log(N) + 2)]; // Form answer, in reverse order, as a string
strcpy(BigNum, "1");
for (Factor = 1; Factor <= N; Factor++) {
Mult(BigNum, Factor);
}
printf("%u! Length:%zu Reverse:\"%s\"\n", Factor - 1, strlen(BigNum), BigNum);
unsigned long Sum = 0;
size_t i;
for (i=0; BigNum[i]; i++) {
Sum += BigNum[i] - '0';
}
printf("Sum of digits:%lu\n", Sum);
return 0;
}
500! Length:1135 Reverse:"000...221"
Sum of digits:4599