Beautiful Arrangement of Numbers in JavaScript

JavascriptWeb DevelopmentFront End Technology

Beautiful Arrangement:

Suppose we have num integers from 1 to num. We define a beautiful arrangement as an array that is constructed by these num numbers successfully if one of the following is true for the ith position (1 ≤ i ≤ N) in this array −

  • The number at the ith position is divisible by i.

  • i is divisible by the number at the ith position.


We are required to write a JavaScript function that takes in a number, num, and returns the count of beautiful arrangements we can construct for num.

For example, if the input to the function is −

const input = 2

Then the output should be −

const output = 2

Output Explanation

The first beautiful arrangement is [1,2]:

The second beautiful arrangement is [2,1]:


The code for this will be −

 Live Demo

const num = 4;
const countArrangements = (num = 1) => {
   let ans = 0
   const recur = (curr, vis) => {
      if (curr === 1){
         for (let i = num; i; i--) {
            let possible = (i % curr === 0 || curr % i === 0);
            let visited = vis & 1 << i;
            if (possible && !visited){
               recur(curr-1, vis | 1 << i);
   recur(num, 0);
   return ans;

Code Explanation:

We define a result variable (ans) and then create a recursive function to navigate the multiple branching possibilities. This recursive function will only need two arguments: which number are we currently looking to place (curr) and which spots have already been visited (vis).


And the output in the console will be −

Published on 03-Mar-2021 10:23:10