Grad shape
Grad shape

Permutations with Divisibility

Get started
hero image
    🙏

    জয়  শ্রী  রাম

    🕉





Problem Statement:


Suppose you have n integers from 1 through n.
A permutation of those n integers is considered a Divisible Permutation if for every i, where 1 <= i <= n, either of the following is true:
  • perm[i] is divisible by i.
  • i is divisible by perm[i].

Given an integer n, find the total number of the valid Divisible Permutations.

Example 1:
Input: n = 2
Output: 2
Explanation:
The first Divisible Permutation is [1,2]:
  • permutation[1] = 1 is divisible by i = 1
  • permutation[2] = 2 is divisible by i = 2

The second Divisible Permutation is [2,1]:
  • permutation[1] = 2 is divisible by i = 1
  • i = 2 is divisible by permutation[2] = 1


Solution:


  • NOTE: I highly recommend going through the Backtracking chapters in the order they are given in the Index page to get the most out of it and be able to build a rock-solid understanding.


Prerequisites:

Algorithm:



Login to Access Content




Java Code:



Login to Access Content


Python Code:



Login to Access Content




Don't forget to take in-depth look at the other backtracking problems in the below link, because that is what would make you comfortable with using the backtracking template and master the art of Backtracking:



Instructor: