Thursday, August 11, 2022
HomeSoftware DevelopmentRely of permutation such that GCD of all components multiplied with place...

Rely of permutation such that GCD of all components multiplied with place isn’t 1

[ad_1]

Given an integer array having N components starting from 1 to N and every factor showing precisely as soon as. The duty is to search out the variety of attainable permutations such that the GCD of all components multiplied with their place is larger than 1.

Notice: As the reply may be very massive, return the reply modulo 109 + 7

Examples:

Enter: N = 2, arr[] = {1, 2}
Output: 1
Clarification: The one legitimate permutation will likely be is [2, 1] as a result of GCD(1*2, 2*1) = 2.

Enter: N = 4, arr[] = {4, 1, 3, 2}
Output: 4
Clarification:
The legitimate permutations will likely be 
[4, 3, 2, 1] with GCD(1*4, 2*3, 3*2, 4*1) = 2.
[2, 3, 4, 1] with GCD(1*2, 2*3, 3*4, 4*1) = 2.
[2, 1, 4, 3] with GCD(1*2, 2*1, 3*4, 4*3) = 2.
[4, 1, 2, 3] with GCD(1*4, 2*1, 3*2, 4*3) = 2.

 

Strategy: The concept to resolve the issue is as follows:

Attempt to make the product of place and the quantity even, then in that state of affairs GCD will likely be not less than 2.
So if N is odd then there’ll 1 more unusual factor than attainable even positions. So no permutation is feasible.
In any other case 

  • the N/2 even components may be organized in (N/2)! methods.
  • For every of this association N/2 odd components may be organized in (N/2)! methods.

So complete variety of attainable methods are ((N/2)!)2.

Comply with the beneath steps to resolve this downside:

  • If N is odd then return 0.
  • Initialize one variable to retailer the reply (say ans = 1).
  • Traverse from i = 1 to N/2.
    • Make ans equal to ans * i * i % MOD.
    • Discover the mod of ans.
  • Return ans.

Under is the implementation of the above method.

C++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

const int MOD = 1000000007;

  

int ValidPerm(int n, int a[])

{

    

    if (n & 1) {

        return 0;

    }

    lengthy lengthy ans = 1;

  

    

    for (int i = 1; i <= n / 2; ++i) {

        ans *= i * i % MOD;

        ans %= MOD;

    }

  

    

    

    return ans;

}

  

int major()

{

    int N = 4;

    int arr[N] = { 1, 3, 2, 4 };

  

    

    cout << ValidPerm(N, arr);

    return 0;

}

Time Complexity: O(N)
Auxiliary House: O(1)

[ad_2]

RELATED ARTICLES

Most Popular

Recent Comments