Skip to content

Commit d115214

Browse files
algorithm: Liouville function (#1100)
1 parent e7ee09a commit d115214

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

Maths/LiouvilleFunction.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
* Author: Akshay Dubey (https://github.com/itsAkshayDubey)
3+
* Liouville Function: https://en.wikipedia.org/wiki/Liouville_function
4+
* For any positive integer n, define λ(n) as the sum of the primitive nth roots of unity.
5+
* It has values in {−1, 1} depending on the factorization of n into prime factors:
6+
* λ(n) = +1 if n positive integer with an even number of prime factors.
7+
* λ(n) = −1 if n positive integer with an odd number of prime factors.
8+
*/
9+
10+
/**
11+
* @function liouvilleFunction
12+
* @description -> This method returns λ(n) of given number n
13+
* returns 1 when number has even number of prime factors
14+
* returns -1 when number has odd number of prime factors
15+
* @param {Integer} number
16+
* @returns {Integer} 1|-1
17+
*/
18+
19+
import { PrimeFactors } from './PrimeFactors.js'
20+
export const liouvilleFunction = (number) => {
21+
if (number <= 0) {
22+
throw new Error('Number must be greater than zero.')
23+
}
24+
return PrimeFactors(number).length % 2 === 0 ? 1 : -1
25+
}

Maths/test/LiouvilleFunction.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { liouvilleFunction } from '../LiouvilleFunction'
2+
3+
const expectedValuesArray = [1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, 1, 1, -1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1, -1, -1, 1]
4+
5+
describe('Testing liouville function', () => {
6+
for (let i = 1; i <= 100; i++) {
7+
it('Testing for number = ' + i + ', should return ' + expectedValuesArray[i], () => {
8+
expect(liouvilleFunction(i)).toBe(expectedValuesArray[i - 1])
9+
})
10+
}
11+
12+
it('should throw error when supplied negative numbers', () => {
13+
expect(() => { liouvilleFunction(-1) }).toThrow(Error)
14+
})
15+
16+
it('should throw error when supplied zero', () => {
17+
expect(() => { liouvilleFunction(0) }).toThrow(Error)
18+
})
19+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy