我遇到了以下计算大型因子(数字大到100)的程序..谁能解释一下这个算法中使用的基本思想?我只需要知道在计算阶乘时实现的数学.
#include <cmath>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
unsigned int d;
unsigned char *a;
unsigned int j, n, q, z, t;
int i,arr[101],f;
double p;
cin>>n;
p = 0.0;
for(j = 2; j <= n; j++)
p += log10(j);
d = (int)p + 1;
a = new unsigned char[d];
for (i = 1; i < d; i++)
a[i] = 0; //initialize
a[0] = 1;
p = 0.0;
for (j = 2; j <= n; j++) …Run Code Online (Sandbox Code Playgroud) 在我的C代码中,我想计算1到100范围内的数字的阶乘.对于小数字,该函数可以工作,但对于更大的数字,例如100!它返回不正确的结果.有什么方法可以处理C中的大数阶因子?我正在使用的编译器是gcc v4.3.3.我的代码如下:
#include <stdio.h>
#include <math.h>
double print_solution(int);
int main(void)
{
int no_of_inputs,n ;
int ctr = 1;
scanf("%d",&no_of_inputs); //Read no of inputs
do
{
scanf("%d",&n); //Read the input
printf("%.0f\n",print_solution(n));
ctr++;
}while(ctr <= no_of_inputs);
return 0;
}
double print_solution(int n)
{
if(n == 0 || n == 1)
return 1;
else
return n*print_solution(n-1);
}
Run Code Online (Sandbox Code Playgroud) 如何编写c ++程序来计算大因子.
例如,如果我想计算(100!)/(99!),我们知道答案是100,但如果我分别计算分子和分母的阶乘,那么这两个数字都是巨大的.
说有一个计算阶乘(n)的函数
factorial(7)是否为1到7中的每一个创建了7个函数对象
并在必要时使用这些值(对于阶乘(8)像阶乘(7)*8)
我无法使用以下代码.
#include <stdio.h>
// I am not sure whethere I should void here or not.
int main() {
// when the first bug is solved, I put here arg[0]. It should be
// similar command line parameter as args[0] in Java.
int a=3;
int b;
b = factorial(a);
// bug seems to be here, since the %1i seems to work only in fprintf
printf("%1i", b);
return 0;
}
int factorial(int x) {
int i;
for(i=1; i<x; i++)
x *= i; …Run Code Online (Sandbox Code Playgroud)