-
Notifications
You must be signed in to change notification settings - Fork 0
/
18. Check_armStrong_number.js
45 lines (40 loc) · 1.36 KB
/
18. Check_armStrong_number.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//*------ check armstrong number
//? This program prompts the user to enter a number and checks whether it's an armstrong number or not.An armstrong number(also known as a narcissistic number or pluperfect digital invariant) is a number that is the sum of its own digits each raised to the power of the number of digits in the number. For example 153 is an ArmStrong number because 13+53+33= 153.
function checkArmStrong(num1) {
if (!isNaN(num1) && num1 > 0 && Number.isInteger(num1)) {
let num = num1;
let numDigits = num.toString().length;
console.log(numDigits);
let sum = 0;
for (let i = 0; i < numDigits; i++) {
sum += Math.pow(parseInt(num.toString()[i]), numDigits);
}
if (sum === num) {
console.log(num + " is an armstrong number");
} else {
console.log(num + " is not an armstrong number");
}
} else {
console.log("Invalid input");
}
}
checkArmStrong(153);
//* method 2
function armStrong(num) {
if (!isNaN(num) && num > 0 && Number.isInteger(num)) {
let originalNum = num;
let sum = 0;
let numLength = num.toString().length;
while (originalNum > 0) {
let digit = originalNum % 10;
sum += digit ** numLength;
originalNum = parseInt(temp / 10);
}
if (sum === num) {
console.log("armstrong");
} else {
console.log("not armstrong");
}
}
}
armStrong(153);