mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 15:39:42 +08:00
algorithm: Liouville function (#1100)
This commit is contained in:
25
Maths/LiouvilleFunction.js
Normal file
25
Maths/LiouvilleFunction.js
Normal file
@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Author: Akshay Dubey (https://github.com/itsAkshayDubey)
|
||||
* Liouville Function: https://en.wikipedia.org/wiki/Liouville_function
|
||||
* For any positive integer n, define λ(n) as the sum of the primitive nth roots of unity.
|
||||
* It has values in {−1, 1} depending on the factorization of n into prime factors:
|
||||
* λ(n) = +1 if n positive integer with an even number of prime factors.
|
||||
* λ(n) = −1 if n positive integer with an odd number of prime factors.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @function liouvilleFunction
|
||||
* @description -> This method returns λ(n) of given number n
|
||||
* returns 1 when number has even number of prime factors
|
||||
* returns -1 when number has odd number of prime factors
|
||||
* @param {Integer} number
|
||||
* @returns {Integer} 1|-1
|
||||
*/
|
||||
|
||||
import { PrimeFactors } from './PrimeFactors.js'
|
||||
export const liouvilleFunction = (number) => {
|
||||
if (number <= 0) {
|
||||
throw new Error('Number must be greater than zero.')
|
||||
}
|
||||
return PrimeFactors(number).length % 2 === 0 ? 1 : -1
|
||||
}
|
19
Maths/test/LiouvilleFunction.test.js
Normal file
19
Maths/test/LiouvilleFunction.test.js
Normal file
@ -0,0 +1,19 @@
|
||||
import { liouvilleFunction } from '../LiouvilleFunction'
|
||||
|
||||
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]
|
||||
|
||||
describe('Testing liouville function', () => {
|
||||
for (let i = 1; i <= 100; i++) {
|
||||
it('Testing for number = ' + i + ', should return ' + expectedValuesArray[i], () => {
|
||||
expect(liouvilleFunction(i)).toBe(expectedValuesArray[i - 1])
|
||||
})
|
||||
}
|
||||
|
||||
it('should throw error when supplied negative numbers', () => {
|
||||
expect(() => { liouvilleFunction(-1) }).toThrow(Error)
|
||||
})
|
||||
|
||||
it('should throw error when supplied zero', () => {
|
||||
expect(() => { liouvilleFunction(0) }).toThrow(Error)
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user