To find factorial of 500 and store it in a variable…and perform calculations…How to store such a huge number?

社会主义新天地 提交于 2019-12-08 01:28:21

问题


how do i store a huge number in a variable (i) and wont need to change much of the program ? Is there a available datatype to store factorial of 100 for example ?

#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();
}

回答1:


There is no built-in language support for such large numbers. You have two options:

  • if you can, use existing library, like GMP
  • implement you own solution

If you decide to take the second path, you might want to consider storing digits (not necesserily decimal) in an array, and perform arithmetic operations using well known school algorithms. Keep in mind it will be (probably considerably) less efficient than heavily optimized library code.




回答2:


@Marcin Łoś is on the money, no C solution without using a library or rolling your own functions.

Follows is a fun, but not imaginative solution where the large number is stored as a array of char (in reverse order).

#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


来源:https://stackoverflow.com/questions/18535998/to-find-factorial-of-500-and-store-it-in-a-variable-and-perform-calculations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!