繁体   English   中英

求数等于其每个数字的阶乘之和,例如:145

[英]Find Number Equal to the sum of factorial of each of its digits eg:145

查找数字等于其每个数字的阶乘总和 eg:145 From 1 to 200 我试过这个:

public static void main(String[] args) {
    int i = 0, x = 0, temp, temp1, digit = 0, factorial = 1, sum = 0;
    System.out.println("Special Numbers from 1 to 10,000 -:");
    for (i = 1; i <= 200; i++) {
        temp = i;
        temp1 = i;
        while (temp > 0) {
            digit = temp % 10;
            factorial = 1;
            for (x = 1; x <= digit; x++) {
                factorial *= x;//factorial of digit
            }
            sum += factorial;//sum of factorial of a all the digits of the number
            temp = temp / 10;
        }
        if (sum == temp1) {
            System.out.println(temp1);
        }
    }
}

所以如果我把 i=145 它工作但否则我得到错误的输出。

您忘记将 sum 设为 0,因此您只能为您尝试的第一个数字获得正确的结果。 sum = 0; 应该在while(temp>0){

您的sum变量是在 for 块之外声明的。

每次计算阶乘总和时,都会将其添加到前一个总和中,因此为1! + 4! + 5! 1! + 4! + 5! 在这种情况下永远不会是145

尝试在循环内将其初始化为0

您需要在for循环内初始化sum

for(i=1;i<=200;i++){
    sum = 0; //<--include this
    temp = i;
    temp1 = i;
    while(temp>0){
        digit = temp%10;
        factorial =1;
        for(x = 1;x<=digit;x++){
            factorial*=x;//factorial of digit
        }
        sum+=factorial; //sum of factorial
        temp = temp/10;
    }
    if(sum == temp1){
        System.out.println(temp1);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM