diff --git a/src/others/armstrong.js b/src/others/armstrong.js new file mode 100644 index 00000000..8b8b95eb --- /dev/null +++ b/src/others/armstrong.js @@ -0,0 +1,40 @@ +/** + * Check if a number is an Armstrong number. + * + * Returns true if the number is an Armstrong number, false otherwise. + * + * @public + * + * @example + * var isArmstrong = require('path-to-algorithms/src/others/armstrong').isArmstrong; + * var result = isArmstrong(153); + * + * console.log(result); // true + * + * @param {Number} num The number to check. + * @returns {boolean} True if the number is an Armstrong number, false otherwise. + * + * @module others/armstrong + */ +(function (exports) { + 'use strict'; + + function isArmstrongNumber(num) { + if (num < 0) { + return false; // Armstrong numbers are non-negative + } + + const numStr = num.toString(); + const numDigits = numStr.length; + let sum = 0; + + for (let i = 0; i < numDigits; i++) { + const digit = parseInt(numStr[i], 10); + sum += Math.pow(digit, numDigits); + } + + return sum === num; + } + + exports.isArmstrong = isArmstrongNumber; +})(typeof window === 'undefined' ? module.exports : window); diff --git a/test/others/armstrong.spec.js b/test/others/armstrong.spec.js new file mode 100644 index 00000000..6f3d22c1 --- /dev/null +++ b/test/others/armstrong.spec.js @@ -0,0 +1,34 @@ +var isArmstrong = require('../../src/others/armstrong.js').isArmstrong; + +describe('isArmstrong', () => { + 'use strict'; + it('should return true for Armstrong numbers', () => { + expect(isArmstrong(0)).toBe(true); // 0 is an Armstrong number + expect(isArmstrong(1)).toBe(true); // 1 is an Armstrong number + expect(isArmstrong(153)).toBe(true); // 153 is an Armstrong number + expect(isArmstrong(9474)).toBe(true); // 9474 is an Armstrong number + }); + + it('should return false for non-Armstrong numbers', () => { + expect(isArmstrong(10)).toBe(false); // 10 is not an Armstrong number + expect(isArmstrong(123)).toBe(false); // 123 is not an Armstrong number + expect(isArmstrong(1234)).toBe(false); // 1234 is not an Armstrong number + expect(isArmstrong(9876)).toBe(false); // 9876 is not an Armstrong number + }); + + it('should return false for negative numbers', () => { + expect(isArmstrong(-153)).toBe(false); // Negative numbers are not Armstrong numbers + expect(isArmstrong(-9474)).toBe(false); // Negative numbers are not Armstrong numbers + }); + + it('should return true for single-digit numbers', () => { + expect(isArmstrong(0)).toBe(true); // 0 is an Armstrong number + expect(isArmstrong(1)).toBe(true); // 1 is an Armstrong number + expect(isArmstrong(9)).toBe(true); // 9 is an Armstrong number + }); + + it('should return true for multi-digit Armstrong numbers', () => { + expect(isArmstrong(153)).toBe(true); // 3^3 + 5^3 + 1^3 = 153 + expect(isArmstrong(9474)).toBe(true); // 9^4 + 4^4 + 7^4 + 4^4 = 9474 + }); +});