Skip to content

Commit 1114140

Browse files
authored
algorithm: check if number is Armstrong number (#44)
1 parent ad59860 commit 1114140

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

Maths/ArmstrongNumber.ts

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @function ArmstrongNumber
3+
* @description Check if the provided number is an Armstrong number or not.
4+
* @summary Armstrong numbers are numbers, the sum of whose digits each raised
5+
* to the power of the number of digits is equal to the number itself.
6+
* For example:
7+
* 370 is an Armstrong number since 3^3 + 7^3 + 0^3 = 370
8+
* (These numbers are also known as Narcissistic numbers, and Pluperfect numbers)
9+
* @param {number} num The number you want to check for
10+
* @return {boolean} Whether the input number is an Armstrong number
11+
* @see [Wikipedia](https://en.wikipedia.org/wiki/Armstrong_number)
12+
* @see [OEIS](https://oeis.org/A005188)
13+
* @example ArmstrongNumber(370) = true
14+
* @example ArmstrongNumber(10) = false
15+
*/
16+
export const ArmstrongNumber = (num: number): boolean => {
17+
if (typeof num !== 'number' || num <= 0) return false;
18+
19+
let compNum = 0
20+
let cloneNum = num
21+
const numOfDigits = Math.floor(1 + Math.log10(num))
22+
23+
while (cloneNum > 0) {
24+
compNum += Math.pow(cloneNum % 10, numOfDigits)
25+
cloneNum = Math.floor(cloneNum / 10)
26+
}
27+
28+
return compNum === num
29+
}

Maths/test/ArmstrongNumber.test.ts

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { ArmstrongNumber } from "../ArmstrongNumber"
2+
3+
test.each([[9, true], [-310, false], [0, false], [407, true], [420, false], [92727, true], [13579, false]])('i is an Armstrong number or not', (num, expected) => {
4+
expect(ArmstrongNumber(num)).toBe(expected)
5+
})

0 commit comments

Comments
 (0)