Skip to content

Commit f3fc0f5

Browse files
feat: add tech number algorithm
1 parent 5c39e87 commit f3fc0f5

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

‎Maths/TechNumber.js‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @function isTechNumber
3+
* @description A tech number is an even digit number where if the number
4+
* is split into two halves, the square of the sum of the two halves
5+
* equals the original number.
6+
* For example, 2025: split into 20 and 25, (20+25)² = 45² = 2025.
7+
* @param {number} n - A positive integer with even number of digits
8+
* @returns {boolean} - True if n is a tech number, false otherwise
9+
* @see https://www.geeksforgeeks.org/tech-number/
10+
* @example isTechNumber(2025) => true
11+
* @example isTechNumber(3025) => true
12+
* @example isTechNumber(1234) => false
13+
*/
14+
const isTechNumber = (n) => {
15+
if (!Number.isInteger(n) || n < 1) {
16+
throw new TypeError('Input must be a positive integer')
17+
}
18+
const str = String(n)
19+
if (str.length % 2 !== 0) return false
20+
const half = str.length / 2
21+
const left = Number(str.slice(0, half))
22+
const right = Number(str.slice(half))
23+
return Math.pow(left + right, 2) === n
24+
}
25+
26+
export { isTechNumber }

‎Maths/test/TechNumber.test.js‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { isTechNumber } from '../TechNumber.js'
2+
3+
describe('isTechNumber', () => {
4+
test('2025 is a tech number (20+25=45, 45²=2025)', () => {
5+
expect(isTechNumber(2025)).toBe(true)
6+
})
7+
8+
test('3025 is a tech number (30+25=55, 55²=3025)', () => {
9+
expect(isTechNumber(3025)).toBe(true)
10+
})
11+
12+
test('9801 is a tech number (98+01=99, 99²=9801)', () => {
13+
expect(isTechNumber(9801)).toBe(true)
14+
})
15+
16+
test('1234 is NOT a tech number', () => {
17+
expect(isTechNumber(1234)).toBe(false)
18+
})
19+
20+
test('odd digit numbers are NOT tech numbers', () => {
21+
expect(isTechNumber(123)).toBe(false)
22+
})
23+
24+
test('100 is NOT a tech number', () => {
25+
expect(isTechNumber(100)).toBe(false)
26+
})
27+
28+
test('81 is a tech number (8+1=9, 9²=81)', () => {
29+
expect(isTechNumber(81)).toBe(true)
30+
})
31+
32+
test('throws TypeError for zero', () => {
33+
expect(() => isTechNumber(0)).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for negative input', () => {
37+
expect(() => isTechNumber(-2025)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for float input', () => {
41+
expect(() => isTechNumber(20.25)).toThrow(TypeError)
42+
})
43+
})

0 commit comments

Comments
 (0)