嵌套循环,无需乘积即可计算阶乘

时间:2019-03-10 17:29:20

标签: c

我正在尝试找出一个C程序,该程序使用无乘法的嵌套while循环来计算阶乘。是否有一种简单的方法来使用尽可能少的变量来做到这一点?

我有一个使用加法进行乘法运算的内部循环,但是我似乎找不到一个可以找到阶乘的外部循环。

#include <stdio.h>
#include <stdlib.h>

int main() {

    unsigned int a = 4;
    unsigned int b = 4;
    unsigned int c = 0;
    int i = 0;

    while(i < b) {
        c += a;
        i++;
    }

    printf("Result: %u", c);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

这是一种解决方案:

#include <stdio.h>

int mult (int n1, int n2);

int main () {
    int number,result,count;
    scanf("%d",&number);
    result=number;
    for (count=number-1;count>1;count--)
        result=mult(result,count);
    printf ("factorial is %d",result);
    return 0;
}

int mult (int n1, int n2) {
    int i,answer=0;
    for (i=1;i<=n2;i++)
        answer+=n1;
    return answer;
}

我使用了自己的变量名,但这不成问题。