Java daffodils number two methods (recursion & loop)

number of daffodils

The so-called daffodil number refers to: an n-digit number (n23), the number of each of its digits is n times The so-called daffodil number refers to: an n-digit number (N23), each of its digits The sum of the nth powers of a number is equal to the sum of its own powers.

For example: 153, 370, 371, 407, etc. are all daffodil numbers. Take 153 for example, 153 = 1*1*1 +5*5*5 +3*3*3. The sum of powers is equal to itself. For example 153, 370, 371, 407, etc. are all daffodils numbers. Take 153 as an example, 153=1*1*1+5*5+3*3.

Satisfying the above conditions is the number of daffodils, otherwise it is not. In the process of writing code, the key point is how to divide the number of daffodils that meets the above conditions, otherwise it is not. In the process of writing code, the key point is how to decompose, how to express the ones, tens, hundreds, etc. in the number . Three integer (int) variables are defined here: int a,b,c.

a=i%10 //decompose each bit

b=i/10%10 //Decompose out the tens

c=i/100%10 //decompose to hundreds

public class Test44 {
    public static void main(String[] args) {
        System.out.println("循环方法");
        isQui1();
        System.out.println("递归方法");
        int i=100;
        isQui2(i);
    }
    //方法二(递归)
    private static int isQui2(int i) {
        if(i!=1000) {
            int a=i%10;
            int b=i/10%10;
            int c=i/100%10;
            if(i==a*a*a+b*b*b+c*c*c){
                System.out.println(i);
            }
            return isQui2(i+1);
        }
        return 0;
    }

    //方法一(循环)
    private static void isQui1() {
        for (int i = 100; i < 1000; i++) {
            int a=i%10;
            int b=i/10%10;
            int c=i/100%10;
            if(i==a*a*a+b*b*b+c*c*c){
                System.out.println(i);
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/m0_62218217/article/details/121483257