Saturday, 16 Oct 2021

# Count permutations of first N natural numbers having sum of adjacent elements equal to a perfect square

Count permutations of first N natural numbers having sum of adjacent elements equal to a perfect squareGiven a positive integer N, the task is to find the number of unique permutations of first N natural numbers having sum of the adjacent elements equal to a perfect square.Examples:Input: N = 17Output: 2Explanation:Following permutations have sum of adjacent elements equal to a perfect square:{17, 8, 1, 15, 10, 6, 3, 13, 12, 4, 5, 11, 14, 2, 7, 9, 16}{16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8, 17}Therefore, count of such permutations is 2.Input: N = 13Output: 0Approach: The given problem can be solved by using the concepts of Graph. Follow the steps below to solve the problem:List all the perfect square numbers up to (2*N – 1) that can be obtained by adding any two positive integers.Represent the graph as the adjacency list representation such that if the sum of two numbers X and Y is a perfect square, then add an edge from node X to node Y.Count the number of nodes in the graph whose in-degree is 1 and store it in a variable X.Now, the number of permutation can be calculated as per the following conditions:If the value of X is 0, then a total of N permutations are possible. Hence, print N as the result.If the value of X is 1 or 2, then a total of 2 permutations are possible. Hence, print 2 as the result.Otherwise, no such permutations exist satisfying the given criteria. Hence, print 0 as the result.Below is the implementation of the above approach:C++#include using namespace std;int countPermutations(int N){        vector adj(105);            int indeg = 0;        for (int i = 1; i