【问题标题】:Finding the Krishnamurthy Number using C使用 C 查找 Krishnamurthy 数
【发布时间】:2020-06-11 18:00:42
【问题描述】:

我只想知道,要找到 Krishnamurthy 数,我们必须先找到数字的阶乘,然后再将这些数字相加。 (例如,1!+4!+5!= 145)。

所以,下面是我的代码,我在那里应用了阶乘函数。但是输出并没有得到支持(145 不是 Kri ......)。

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

void main()
{
    int digit,factorial = 1, temp, input, sum = 0;
    printf("Enter a Number:\n");
    scanf("%d",&input);
    int Factorial(int digit){

         factorial = factorial*digit;
         return 0;
    }
    temp = input;
    while(temp>0){
        digit = temp%10;
        temp = temp/10;
        sum = sum + Factorial(digit);
    }
    if(sum==input){
        printf("%d is a Krishnamurthy Number",input);
    }
    else{
        printf("%d is not a Krishnamurthy Number",input);
    }


}

我在逻辑、函数声明或定义上做错了吗?请帮忙。

【问题讨论】:

  • 函数内部不能有函数。
  • @Eraklon 是的,我已经改变了,但仍然没有得到想要的输出
  • 不确定你在用 Factorial 函数做什么(例如 4! = 4*3*2*1 那么该函数如何产生 24?) - 但因为只有 10 位数的可能性为什么不创建一个包含 10 个可能的阶乘的数组 [10] 并按 digit 对其进行索引。
  • Krishnamurthy 数的集合是有限的吗?

标签: dynamic-programming


【解决方案1】:

您的阶乘函数未正确执行。阶乘意味着,从 n 到 1 的所有数字的乘法 -

(n-1) * (n-2) * ... * (n)

但是你的函数没有给出你想要的结果。

int Factorial(int digit){
     factorial = factorial*digit;
     return 0;
}

您需要更改该函数以获取数字的阶乘值,您可以将循环迭代到一个或使用递归方法来获取阶乘。

int Factorial(int digit){
     int result = 1;
     for(int i=n; i>=1; i--){
        result *= i;
     }
     return result;
}

int Factorial(int digit) {
    if(n <= 1) return digit;

    return digit * Factorial(digit-1);
}

大家可以关注thread了解上面提到的递归函数的深度。

【讨论】:

    【解决方案2】:
    #include<stdio.h>
    int main(int argc, char* argv[], char* envp[])
    {
    int sum = 0, 
    int a, 
    int p = 0, 
    int d, 
    int i, 
    int fact;
    
    //code
    printf("Enter a number: ");
    scanf("%d", &a);
    p = a;
    
    while (a > 0)
    {
    fact = 1;
        d = a % 10;
        a /= 10;
        for (i = d; i >= 1; i--)
        {
            fact *= i;
        }
        sum += fact;
    }
    
    if (sum == p)
        printf("It is a Krishnamurthy number.\n");
    else
        printf("It is not a Krishnamurthy number.\n");
    
    printf("\n\n");
    
    return(0);
    }
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2011-04-29
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 2021-07-08
    • 2011-08-21
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    相关资源
    最近更新 更多