How to use JavaScript programming to find the number of daffodils: 1. Use a for loop to search and traverse all three digits; 2. Determine whether the traversed number is the sum of the third power of the number in each digit. The number itself; 3. Select a number in the hundreds place; 4. Use the if statement to determine whether i is a daffodil number.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to use javascript programming to find the number of narcissus?
First we need to know what the number of narcissus is:
Narcissistic number Also known as pluperfect digital invariant (PPDI), narcissistic number, autoexponential number, Armstrong number or Armstrong number, the narcissus number refers to a 3-digit number , the sum of the 3rd power of the numbers in each digit is equal to itself. For example: 1^3 5^3 3^3 = 153.
Obtain the number of daffodils through JS:
Idea analysis:
1. Use a for loop to find and traverse all three-digit numbers from 100 to 999 ;
2. Determine whether the traversed number is the sum of the three powers of the numbers in each digit and whether it is equal to the number itself. If it is, it is the daffodil number, and output it on the console (how to select each digit Number)
(1) Select the single digit modulo 10, and the remainder is the single digit
(2) Select the tens digit, divide i by 10, and then round the result , after rounding, a two-digit integer is obtained. Use this result to take modulo 10 and get the tens digit
(3) Select the hundreds digit. Divide the three-digit number by 100 and then round to the whole to get the hundreds digit.
3. Use the if statement to determine whether i is a narcissus number. The Math object is used to perform mathematical tasks, and the pow(x, y) function is used to find x raised to the y power.
for(var i = 100;i<=999;i++){ var gw = i%10; var sw = parseInt(i/10) % 10; var bw = parseInt(i/100); if(i == Math.pow(gw,3)+Math.pow(sw,3)+Math.pow(bw,3)){ console.log(i); } }
The output result is:
Recommended study: "javascript basic tutorial"
The above is the detailed content of How to calculate the number of daffodils using javascript programming. For more information, please follow other related articles on the PHP Chinese website!