我可以找到1个数字是否是krishnamoorthy数字,但我需要找到10个数字

c2e8gylq  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(351)

krishnamoorthy数是一个数字的阶乘和等于该数本身的数(例:145=1!+4! + 5!) 我目前的程序可以找到一个数字是否是克里希纳穆尔西数,但我尝试接受10个数字,并显示其中哪些是克里希纳穆尔西数。

import java.util.Scanner;
public class krishnamoorthy {
  static int fact(int number)   
    {   
        int f = 1;   
        while (number != 0) {   
            f = f * number;   
            number--;   
        }   
        return f;   
    }   
    static boolean checkNumber(int number)   
    {   
        int sum = 0;                
        int tempNumber = number;     
        while (tempNumber != 0) {   
            sum = sum + fact(tempNumber % 10);   
            tempNumber = tempNumber / 10;   
        }   
        if(sum == number)  
            return true;  
        else  
            return false;  
    }   

    public static void main(String[] args)   
    {   
        int n;   
        Scanner sc = new Scanner(System.in);   
        System.out.println("Enter any number:");    
        n = sc.nextInt();           
        if (checkNumber(n))   
            System.out.println(n + " is a krishnamurthy number");   
        else  
            System.out.println(n + "is not a krishnamurthy number");   
    }
}
yhuiod9q

yhuiod9q1#

public class krishnamoorthy {

    public static void main(String... args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("How many numbers: ");
        int total = scan.nextInt();
        System.out.format("Enter %d numbers:\n", total);

        for (int i = 0; i < total; i++) {
            int num = scan.nextInt();

            if (isKrishnamoorthy(num))
                System.out.format("%d is a krishnamurthy number\n", num);
            else
                System.out.format("%d is not a krishnamurthy number\n", num);
        }
    }

    private static boolean isKrishnamoorthy(int num) {
        int sum = num;

        while (num != 0) {
            sum -= fact(num % 10);
            num /= 10;
        }

        return sum == 0;
    }

    private static int fact(int num) {
        int res = 1;

        for (int i = 2; i <= num; i++)
            res *= i;

        return res;
    }

}

相关问题