Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
Collatz Sequence for all numbers from 1 to 10 stored in individual arrays

I want to produce Collatz Sequence for all numbers from 1 to 10 and all the produced sequences are stored in an array named innerArr that should change at every looping. And all those changed arrays are to be stored in outerArr (i.e. array of arrays). But:

1. Given for loop not incrementing (or decrementing) when there exists a while loop inside this for loop.

2. Given while loop is working only when there is no for loop covering it and n = (any number).

   let n,outerArr = []; 
   for (n = 1; n < 10; n++) {
      let innerArr = [], i = 0;
      innerArr.push(n);
    
      while (n !== 1) {
        if (n % 2 == 0) {
          n = n / 2;
          innerArr.push(n);
        }  else {
          n = (3 * n) + 1;
          innerArr.push(n);
        }
        i++;
      }
      outerArr.push(innerArr);
    }
    console.log(outerArr) 
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is, that your for loop, that tries to count n from 1 to 9, will never run through the end, because n is always reset to 1 in the while loop. Therefore you must separate the variables that count from 1 to 9, and the variable that is modified in the while loop.

Moreover, if you really want to cover the numbers from 1 to 10 as you say in your question, remember to use <= 10.

   let n,outerArr = []; 
   for (m = 1; m <= 10; m++) {
      let n = m;
      let innerArr = [], i = 0;
      innerArr.push(n);
    
      while (n !== 1) {
        if (n % 2 == 0) {
          n = n / 2;
          innerArr.push(n);
        }  else {
          n = (3 * n) + 1;
          innerArr.push(n);
        }
        i++;
      }
      outerArr.push(innerArr);
    }
    console.log(outerArr) 

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!