DEV Community


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) {
  var pairs = [].concat(, 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 = []
    var z = a.toString().split(',')
    var result = {
      return parseInt(x, 10)
    for(var i=0;i<n;i++){

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

Top comments (2)

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!

ekremsel profile image
Ekrem • Edited

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

Want to Create an Account?
Now it's your turn!
🗒 Share a tutorial
🤔 Reflect on your coding journey
❓ Ask a question

Create an account to join hundreds of thousands of DEV members on their journey.