Converting mathematical formula into node.js

Viewed 828

I want to use the mathematical formula as listed here:

https://en.wikipedia.org/wiki/Necklace_(combinatorics)#Number_of_bracelets

in node.js to calculate the total number of unique ring sequences I can generate of n length using k characters, allowing for repetition, and ignoring mirrored sequences

This formula requires the previous formula also be calculated, as listed here:

https://en.wikipedia.org/wiki/Necklace_(combinatorics)#Number_of_necklaces

The results of this "Number of necklaces" formula is used as Nk(n) in the "Number of bracelets" formula.

EDIT

here is the final solution:

const phi = require('number-theory').eulerPhi
const divisors = require('number-theory').divisors

let n = 6,
  k = 5,
  sum = (arr, func) => arr.reduce( (acc, n) => acc + func(n), 0),
  divisorsArray = divisors(n),
  necklaces = (1/n) * sum(divisorsArray, (d) => phi(d) * k ** (n/d))

let bracelets = (n % 2) ?
  (necklaces/2) + 0.5 * (k ** ((n+1)/2)) :
  (necklaces/2) + 0.25 * (k+1) * (k ** (n/2))
1 Answers

Here is the final solution, which works correctly for me

const phi = require('number-theory').eulerPhi
const divisors = require('number-theory').divisors

let n = 6,
    k = 5,
    sum = (arr, func) => arr.reduce( (acc, n) => acc + func(n), 0),
    divisorsArray = divisors(n),
    necklaces = (1/n) * sum(divisorsArray, (d) => phi(d) * k ** (n/d))

let bracelets = (n % 2) ?
    (necklaces/2) + 0.5 * (k ** ((n+1)/2)) :
    (necklaces/2) + 0.25 * (k+1) * (k ** (n/2))
Related