Skip to content

algorithm: check if number is Armstrong number #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Oct 15, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Maths/ArmstrongNumber.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @function ArmstrongNumber
* @description Check if the provided number is an Armstrong number or not.
* @summary Armstrong numbers are numbers, the sum of whose digits each raised
* to the power of the number of digits is equal to the number itself.
* For example:
* 370 is an Armstrong number since 3^3 + 7^3 + 0^3 = 370
* (These numbers are also known as Narcissistic numbers, and Pluperfect numbers)
* @param {number} num The number you want to check for
* @return {boolean} Whether the input number is an Armstrong number
* @see [Wikipedia](https://en.wikipedia.org/wiki/Armstrong_number)
* @see [OEIS](https://oeis.org/A005188)
* @example ArmstrongNumber(370) = true
* @example ArmstrongNumber(10) = false
*/
export const ArmstrongNumber = (num: number): boolean => {
if (typeof num !== 'number' || num <= 0) return false;

let compNum = 0

const digitArr = num
.toString()
.split('');

digitArr.map((digit) => compNum += Math.pow(Number(digit), digitArr.length))

return num === compNum
}
27 changes: 27 additions & 0 deletions Maths/test/ArmstrongNumber.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { ArmstrongNumber } from "../ArmstrongNumber"

describe('ArmstrongNumber', () => {
it('should return the correct value', () => {
expect(ArmstrongNumber(9)).toBe(true)
})
it('should return the correct value', () => {
expect(ArmstrongNumber(-310)).toBe(false)
})
it('should return the correct value', () => {
expect(ArmstrongNumber(407)).toBe(true)
})
it('should return the correct value', () => {
expect(ArmstrongNumber(420)).toBe(false)
})
it('should return the correct value', () => {
expect(ArmstrongNumber(0)).toBe(false)
})

it('should return the correct value', () => {
expect(ArmstrongNumber(13579)).toBe(false)
})

it('should return the correct value', () => {
expect(ArmstrongNumber(92727)).toBe(true)
})
})