Skip to content

Commit 4100091

Browse files
feat: add Automorphic Numbers and tests in Math (TheAlgorithms#1496)
* feat: add automorphic number and tests * fix: add spaces * fix: merge tests with test.each
1 parent 05e3248 commit 4100091

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

Maths/AutomorphicNumber.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @function isAutomorphic
3+
* @author [SilverDragonOfR] (https://github.com/SilverDragonOfR)
4+
*
5+
* @see [Automorphic] (https://en.wikipedia.org/wiki/Automorphic_number)
6+
* @description This script will check whether a number is Automorphic or not
7+
* @description A number n is said to be a Automorphic number if the square of n ends in the same digits as n itself.
8+
*
9+
* @param {Integer} n - the n for nth Catalan Number
10+
* @return {Integer} - the nth Catalan Number
11+
* @complexity Time: O(log10(n)) , Space: O(1)
12+
*
13+
* @convention We define Automorphic only for whole number integers. For negetive integer we return False. For float or String we show error.
14+
* @examples 0, 1, 5, 6, 25, 76, 376, 625, 9376 are some Automorphic numbers
15+
*/
16+
17+
// n is the number to be checked
18+
export const isAutomorphic = (n) => {
19+
if (typeof n !== 'number') {
20+
throw new Error('Type of n must be number')
21+
}
22+
if (!Number.isInteger(n)) {
23+
throw new Error('n cannot be a floating point number')
24+
}
25+
if (n < 0) {
26+
return false
27+
}
28+
29+
// now n is a whole number integer >= 0
30+
let n_sq = n * n
31+
while (n > 0) {
32+
if (n % 10 !== n_sq % 10) {
33+
return false
34+
}
35+
n = Math.floor(n / 10)
36+
n_sq = Math.floor(n_sq / 10)
37+
}
38+
39+
return true
40+
}

Maths/test/AutomorphicNumber.test.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { isAutomorphic } from '../AutomorphicNumber'
2+
3+
describe('AutomorphicNumber', () => {
4+
it('should throw Error when n is String', () => {
5+
expect(() => isAutomorphic('qwerty')).toThrow()
6+
})
7+
it('should throw Error when n is floating point', () => {
8+
expect(() => isAutomorphic(13.6)).toThrow()
9+
})
10+
11+
test.each([
12+
{ n: -3 , expected: false },
13+
{ n: -25 , expected: false },
14+
])('should return false when n is negetive', ({ n, expected }) => {
15+
expect(isAutomorphic(n)).toBe(false)
16+
})
17+
18+
test.each([
19+
{ n: 7 , expected: false },
20+
{ n: 83 , expected: false },
21+
{ n: 0 , expected: true },
22+
{ n: 1 , expected: true },
23+
{ n: 376 , expected: true },
24+
{ n: 90625 , expected: true },
25+
])('should return $expected when n is $n', ({ n, expected }) => {
26+
expect(isAutomorphic(n)).toBe(expected)
27+
})
28+
})

0 commit comments

Comments
 (0)