本文介绍了要查找的500阶乘并将其存储在一个变量...并执行计算...如何存储这样一个庞大的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何存储在一个变量(i)一个庞大的数字,并不会需要改变很多的程序?
是否有可用的数据类型来存储100阶乘例如?
#包括LT&;&stdio.h中GT;
#包括LT&;&CONIO.H GT;无效的主要()
{ 长长的INT I = 1;
得到long long int总和= 0;
得到long long int J = 0;
长长的INT位= 0; 为(J = 500; J> = 1; j--)
{
I = I *焦耳; }
的printf(%LLD我); 而(ⅰ大于0)
{
数字= I%10;
I = I / 10;
总和=总和+数字;
} 的printf(\\ N%LLD,总和); 残培();
}
解决方案
@Marcin洛杉矶是在钱上,而无需使用库或滚动你自己的函数没有C的解决方案。
下面是一种乐趣,而不是富有想象力的解决方案,其中大量的存储为一个数组字符
(以相反的顺序)。
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
#包括LT&;&math.h中GT;无效MULT(字符* BIGNUM,无符号因子){
无符号累加器= 0;
字符数字;
而((数字= * BIGNUM)!='\\ 0'){
累加器+ =((符号)(数字 - '0'))*因子;
* BIGNUM ++ =累加器%10 +'0';
累加器/ = 10;
}
而(累加器大于0){
* BIGNUM ++ =累加器%10 +'0';
累加器/ = 10;
}
* BIGNUM ='\\ 0';
}诠释主(){
无符号的N = 500;
无符号的因素;
CHAR BIGNUM [(为size_t)(N *日志(N)+ 2)]; //形式的答案,以相反的顺序,以字符串形式
的strcpy(BIGNUM,1);
对于(因子= 1;因子VIII = N;因子++){
MULT(BIGNUM,因子);
}
的printf(!%U长度:%祖反转:\\%s \\的\\ n,因子 - 1,strlen的(BIGNUM),BIGNUM);
无符号长总和= 0;
为size_t我;
对于(i = 0; BIGNUM [I];我++){
总和+ = BIGNUM [I] - '0';
}
的printf(数字总和:%lu个\\ N,总和);
返回0;
}
500!长度:1135反向:000 ... 221
数字总和:4599
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();
}
解决方案
@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
这篇关于要查找的500阶乘并将其存储在一个变量...并执行计算...如何存储这样一个庞大的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!