From dc675062722d2a10b23af2e9b95a6164121f35ca Mon Sep 17 00:00:00 2001 From: Akshay Dubey <38462415+itsAkshayDubey@users.noreply.github.com> Date: Wed, 25 May 2022 17:39:23 +0530 Subject: [PATCH] merge: Add pronic number implementation (#1023) * feat: Add pronic number implementation * Add test to Math * Minor fixes * Minor style fixes * refactor: Store square root in a variable * Minor refactoring * fix: Change pronic number check logic Reduced time complexity from O(sqrt(n)) to O(1) * Minor style fixes * fix: Update pronic number check boolean equation * refactor: Change pronic number check condition * refactor: Add tests to Math * Minor style fixes * refactor: Change unit test logic --- Maths/IsPronic.js | 27 +++++++++++++++++++++++++++ Maths/test/IsPronic.test.js | 12 ++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 Maths/IsPronic.js create mode 100644 Maths/test/IsPronic.test.js diff --git a/Maths/IsPronic.js b/Maths/IsPronic.js new file mode 100644 index 000000000..878cdbc80 --- /dev/null +++ b/Maths/IsPronic.js @@ -0,0 +1,27 @@ +/* + * Author: Akshay Dubey (https://github.com/itsAkshayDubey) + * Pronic Number: https://en.wikipedia.org/wiki/Pronic_number + * function to check if number is pronic. + * return true if number is pronic. + * else false + */ + +/** + * @function isPronic + * @description -> Checking if number is pronic using product of two consecutive numbers + * If number is a product of two consecutive numbers, then it is pronic + * therefore, the function will return true + * + * If number is not a product of two consecutive numbers, then it is not pronic + * therefore, the function will return false + * @param {number} number + * @returns {boolean} + */ + +export const isPronic = (number) => { + if (number === 0) { + return true + } + const sqrt = Math.sqrt(number) + return sqrt % 1 !== 0 && Math.ceil(sqrt) * Math.floor(sqrt) === number +} diff --git a/Maths/test/IsPronic.test.js b/Maths/test/IsPronic.test.js new file mode 100644 index 000000000..7ec957ce3 --- /dev/null +++ b/Maths/test/IsPronic.test.js @@ -0,0 +1,12 @@ +import { isPronic } from '../IsPronic' + +const pronicNumbers = [0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462, 506, 552, 600, 650, 702, 756, 812, 870, 930, 992, 1056, 1122, 1190, 1260, 1332, 1406, 1482, 1560, 1640, 1722, 1806, 1892, 1980, 2070, 2162, 2256, 2352, 2450, 2550] + +describe('Testing isPronic function', () => { + for (let i = 0; i <= 2500; i++) { + it('should return true', () => { + const isPronicNumber = isPronic(i) + expect(isPronicNumber).toBe(pronicNumbers.includes(i)) + }) + } +})