Use native JS to find out the number of daffodils

Time:2021-4-7

Narcissus number:A three digit integer, the sum of cubes of number, ten and hundred is equal to the integer (example: 153 = 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3)

Step idea:
1. Loop through in turn, output all three digits, rounding
2. Set condition judgment
3. Store output to array

Method 1: direct digital

Var arr = [] // all Narcissus numbers are a collection array
    for (var i = 100; i < 1000; i++) { 
        Var a = I% 10; // take out the digits
        Var B = parseInt (I% 100 / 10); // take out ten digits, small method 2: ((I / 10)% 10)
        Var C = parseInt (I / 100); // take out 100 digits
        If (a * a * a + b * b * B + C * C = = = I) {// use the narcissus number condition to judge
            arr.push (i) ; // add if it meets the conditions
        }
    }
    console.log(arr); // [153, 370, 371, 407]

Method 2: take string to number

var newArr = []
    for (var i = 100; i <= 999; i++) { 
        var str_i = i.toString();
        var hundred = Number(str_ i. Charat (0)); // use charat (index) function to find hundreds
        var ten = Number(str_ i. Charat (1)); // find ten digits
        var dig = Number(str_ i. Charat (2)); // find one digit
        var result =  Math.pow (hundred, 3) +  Math.pow (ten, 3) +  Math.pow (dig, 3); // use Math.pow (variable, power) to achieve cubic operation
        If (result = = I) // use the narcissus number condition to judge
        {
            newArr.push(i)
        }
    }
    console.log(newArr); // [153, 370, 371, 407]