DEV Community

Ekrem
Ekrem

Posted on • Updated on

Calling a function on an array pair

function lcmCardinality(n) {
  var factors = []
  for (var i = 1; i <= n; i++) {
    if (n % i == 0) {
      factors.push(i)
    }
  }
  var pairs = [].concat(
    ...factors.map((v, i) => factors.slice(i).map(w => v + ',' + w))
  )
  function gcd(x, y) {
    if (typeof x !== 'number' || typeof y !== 'number') return false
    x = Math.abs(x)
    y = Math.abs(y)
    while (y) {
      var t = y
      y = x % y
      x = t
    }
    return x
  }
  function lcm(a, b) {
    return (a / gcd(a, b)) * b
  }
  for (var i = 0; i < pairs.length; i++) {
    var d = pairs[i]
    var a = []
    a.push(d)
    var z = a.toString().split(',')
    var result = z.map(function(x) {
      return parseInt(x, 10)
    })
    for(var i=0;i<n;i++){
if(lcm(...result)==n){
console.log(lcm(...result))}};
  }
}

The code times out. I am having trouble getting the lcm(...result) where it equals n.

Top comments (2)

Collapse
 
lingeringsmell profile image
Annie Hall

Hi, on the off chance this is still troubling you, here's the fix for the problems you're seeing:

When you're creating the pairs array, you're missing the "n, 1" pair. Therefore pairs is empty when n = 1 and you miss one of the lcm = 12 pairs when n = 12.
To fix this you can call the slice function with i as opposed to i+1

Additionally, while this won't affect your output as such, the for loop you use to iterate over pairs should read i < pairs.length. When i = pairs.length, then pairs[i] is undefined.
Then you can skip the handling steps of pairs[i] using variables a and d and directly assign z = pairs[i].split(",")

Hope that helps!

Collapse
 
ekremsel profile image
Ekrem • Edited

Thank you kind stranger :) I am having trouble returning as a stand alone value