Open In App

Count pairs with GCD 1 by incrementing n and m in each step

Last Updated : 11 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two integers n and m. Find the number of continuous pairs possible with gcd(n, m) = 1, wherein each step 1 can be incremented to the pair.

Examples:

Input: n = 1, m = 4
Output: 2
Explanation: gcd(1, 4) =1, in the next step gcd(2, 5) =1 so the maximum possible continuous pairs are 2.

Input: n = 5, m = 13
Output:1
Explanation: Only that pair is possible with gcd(n, m) =1 because in the next step n = 6, m = 14 which has gcd = 2 so the output is 1.

Approach: This can be solved with the below idea:

We need to find the k such that gcd(n+k, m+k) is greater than 2, so there should be at least 1 prime number that divides both n+k, and m+k, excluding exceptional cases when n=m and n = m+1. There should be a number p that divides both m+k and n+k.

  • m+k = n1 *p
  • n+k = n2*p

Hence the difference (n-m) % p = 0, so we only need to look at prime factors of n-m such that n+k % p =0 so we take the minimum value of p – n%p which is the number of steps it can be incremented so that gcd (n, m) is 1.

Follow the steps mentioned below to solve the problem:

  • Build the sieve to store the smallest prime factors
  • Find the current gcd and if the initial gcd is not equal to 1 then return 0.
  • Swap n, m if n > m
  • Find the difference and check if the difference is 1, If the difference is 1 return -1 since gcd will be 1 for infinite steps
  • Find all the prime factors of the difference using factorize function.
  • Initialize the variable pairs to find the number of continuous pairs
  • Iterate through the prime factors and check the pairs that are possible by taking a minimum of p-n%p. Return the number of pairs

Below is the implementation of the above approach:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
int N = 10000005;
vector<long long> spf(N + 1, 1);
 
// Build the sieve to store
// smallest prime factors
void build_sieve()
{
    long long i, j;
    for (i = 2; i < N; i++) {
        if (spf[i] == 1) {
            spf[i] = i;
            for (j = i * i; j <= N; j += i) {
                if (spf[j] == 1)
                    spf[j] = i;
            }
        }
    }
}
// Function to get the prime
// factor of the number n
vector<int> factorize(int n)
{
    vector<int> ans;
    while (n > 1) {
        int fact = spf[n];
        while (n % fact == 0) {
            n /= fact;
        }
        ans.push_back(fact);
    }
    return ans;
}
 
// Function to find the maximum
// possible continuous pairs
int find_maxpairs(int n, int m)
{
 
    // Calling the build_sieve
    build_sieve();
 
    // Find the current gcd and if initial
    // gcd is not equal to 1 then return 0.
    int gcd = __gcd(n, m);
    if (gcd != 1) {
        return 0;
    }
 
    // Swap n, m if n > m
    if (n > m)
        swap(n, m);
 
    // Find the difference and check if
    // the difference is 1, If the
    // difference is 1 return -1 since
    // gcd will be 1 for infinite steps
    int diff = m - n;
 
    if (diff == 1) {
        return -1;
    }
 
    // Find all the prime factors
    // of the difference
    vector<int> prime_factors = factorize(diff);
 
    // Initialize the variable pairs to
    // find the number of continuous pairs
    int pairs = INT_MAX;
 
    // Iterate through the prime factors
    // and check the pairs that
    // are possible.
    for (auto p : prime_factors) {
        int to_be_added = p - (n % p);
        pairs = min(pairs, to_be_added);
    }
 
    // Return the number of pairs
    return pairs;
}
 
// Driver Code
int main()
{
    int n = 1;
    int m = 4;
 
    // Function call
    cout << find_maxpairs(n, m) << endl;
    return 0;
}


Java




import java.util.*;
 
public class Main {
 
    static int N = 10000005;
    static ArrayList<Long> spf
        = new ArrayList<>(Collections.nCopies(N + 1, 1L));
 
    // Build the sieve to store
    // smallest prime factors
    static void build_sieve()
    {
        for (long i = 2; i < N; i++) {
            if (spf.get((int)i) == 1) {
                spf.set((int)i, i);
                for (long j = i * i; j <= N; j += i) {
                    if (spf.get((int)j) == 1) {
                        spf.set((int)j, i);
                    }
                }
            }
        }
    }
 
    // Function to get the prime
    // factor of the number n
    static ArrayList<Integer> factorize(int n)
    {
        ArrayList<Integer> ans = new ArrayList<>();
        while (n > 1) {
            int fact = (int)(long)spf.get(n);
            while (n % fact == 0) {
                n /= fact;
            }
            ans.add(fact);
        }
        return ans;
    }
 
    static int gcd(int a, int b)
    {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }
 
    // Function to find the maximum
    // possible continuous pairs
    static int find_maxpairs(int n, int m)
    {
        // Calling the build_sieve
        build_sieve();
 
        // Find the current gcd and if initial
        // gcd is not equal to 1 then return 0.
        int gcd = gcd(n, m);
        if (gcd != 1) {
            return 0;
        }
 
        // Swap n, m if n > m
        if (n > m) {
            int temp = n;
            n = m;
            m = temp;
        }
 
        // Find the difference and check if
        // the difference is 1, If the
        // difference is 1 return -1 since
        // gcd will be 1 for infinite steps
        int diff = m - n;
 
        if (diff == 1) {
            return -1;
        }
 
        // Find all the prime factors
        // of the difference
        ArrayList<Integer> prime_factors = factorize(diff);
 
        // Initialize the variable pairs to
        // find the number of continuous pairs
        int pairs = Integer.MAX_VALUE;
 
        // Iterate through the prime factors
        // and check the pairs that
        // are possible.
        for (int p : prime_factors) {
            int to_be_added = p - (n % p);
            pairs = Math.min(pairs, to_be_added);
        }
 
        // Return the number of pairs
        return pairs;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int n = 1;
        int m = 4;
 
        // Function call
        System.out.println(find_maxpairs(n, m));
    }
}
 
// This code is contributed by Prajwal Kandekar


Python3




import math
 
N = 10000005
spf = [1]*(N+1)
 
# Build the sieve to store
# smallest prime factors
 
 
def build_sieve():
    global spf
 
    for i in range(2, N):
        if spf[i] == 1:
            spf[i] = i
            for j in range(i*i, N+1, i):
                if spf[j] == 1:
                    spf[j] = i
 
# Function to get the prime
# factor of the number n
 
 
def factorize(n):
    ans = []
    while n > 1:
        fact = spf[n]
        while n % fact == 0:
            n //= fact
        ans.append(fact)
    return ans
 
# Function to find the maximum
# possible continuous pairs
 
 
def find_maxpairs(n, m):
    global spf
 
    # Calling the build_sieve
    build_sieve()
 
    # Find the current gcd and if initial
    # gcd is not equal to 1 then return 0.
    gcd = math.gcd(n, m)
    if gcd != 1:
        return 0
 
    # Swap n, m if n > m
    if n > m:
        n, m = m, n
 
    # Find the difference and check if
    # the difference is 1, If the
    # difference is 1 return -1 since
    # gcd will be 1 for infinite steps
    diff = m - n
 
    if diff == 1:
        return -1
 
    # Find all the prime factors
    # of the difference
    prime_factors = factorize(diff)
 
    # Initialize the variable pairs to
    # find the number of continuous pairs
    pairs = float('inf')
 
    # Iterate through the prime factors
    # and check the pairs that
    # are possible.
    for p in prime_factors:
        to_be_added = p - (n % p)
        pairs = min(pairs, to_be_added)
 
    # Return the number of pairs
    return pairs
 
 
# Driver Code
n = 1
m = 4
 
# Function call
print(find_maxpairs(n, m))


C#




// C# code implementation
 
using System;
using System.Collections.Generic;
 
public class GFG {
 
    static int N = 10000005;
    static List<long> spf = new List<long>(new long[N + 1]);
 
    // Build the sieve to store smallest prime factors
    static void BuildSieve()
    {
        for (long i = 2; i < N; i++) {
            if (spf[(int)i] == 0) {
                spf[(int)i] = i;
                for (long j = i * i; j <= N; j += i) {
                    if (spf[(int)j] == 0) {
                        spf[(int)j] = i;
                    }
                }
            }
        }
    }
 
    // Function to get the prime factor of the number n
    static List<int> Factorize(int n)
    {
        List<int> ans = new List<int>();
        while (n > 1) {
            int fact = (int)(long)spf[n];
            while (n % fact == 0) {
                n /= fact;
            }
            ans.Add(fact);
        }
        return ans;
    }
 
    static int Gcd(int a, int b)
    {
        if (b == 0) {
            return a;
        }
        return Gcd(b, a % b);
    }
 
    // Function to find the maximum possible continuous
    // pairs
    static int FindMaxPairs(int n, int m)
    {
        // Calling the BuildSieve
        BuildSieve();
 
        // Find the current gcd and if initial gcd is not
        // equal to 1 then return 0.
        int gcd = Gcd(n, m);
        if (gcd != 1) {
            return 0;
        }
 
        // Swap n, m if n > m
        if (n > m) {
            int temp = n;
            n = m;
            m = temp;
        }
 
        // Find the difference and check if the difference
        // is 1, If the difference is 1 return -1 since gcd
        // will be 1 for infinite steps
        int diff = m - n;
 
        if (diff == 1) {
            return -1;
        }
 
        // Find all the prime factors of the difference
        List<int> prime_factors = Factorize(diff);
 
        // Initialize the variable pairs to find the number
        // of continuous pairs
        int pairs = Int32.MaxValue;
 
        // Iterate through the prime factors and check the
        // pairs that are possible.
        foreach(int p in prime_factors)
        {
            int to_be_added = p - (n % p);
            pairs = Math.Min(pairs, to_be_added);
        }
 
        // Return the number of pairs
        return pairs;
    }
 
    static public void Main()
    {
 
        // Code
        int n = 1;
        int m = 4;
 
        // Function call
        Console.WriteLine(FindMaxPairs(n, m));
    }
}
 
// This code is contributed by lokesh.


Javascript




const N = 10000005;
let spf = new Array(N + 1).fill(0);
 
// Build the sieve to store smallest prime factors
function buildSieve() {
  for (let i = 2; i < N; i++) {
    if (spf[i] == 0) {
      spf[i] = i;
      for (let j = i * i; j <= N; j += i) {
        if (spf[j] == 0) {
          spf[j] = i;
        }
      }
    }
  }
}
 
// Function to get the prime factor of the number n
function factorize(n) {
  let ans = [];
  while (n > 1) {
    let fact = spf[n];
    while (n % fact == 0) {
      n /= fact;
    }
    ans.push(fact);
  }
  return ans;
}
 
function gcd(a, b) {
  if (b == 0) {
    return a;
  }
  return gcd(b, a % b);
}
 
// Function to find the maximum possible continuous pairs
function findMaxPairs(n, m) {
  // Calling the BuildSieve
  buildSieve();
 
  // Find the current gcd and if initial gcd is not
  // equal to 1 then return 0.
  let GCD = gcd(n, m);
  if (GCD != 1) {
    return 0;
  }
 
  // Swap n, m if n > m
  if (n > m) {
    [n, m] = [m, n];
  }
 
  // Find the difference and check if the difference
  // is 1, If the difference is 1 return -1 since gcd
  // will be 1 for infinite steps
  let diff = m - n;
 
  if (diff == 1) {
    return -1;
  }
 
  // Find all the prime factors of the difference
  let prime_factors = factorize(diff);
 
  // Initialize the variable pairs to find the number
  // of continuous pairs
  let pairs = Number.MAX_SAFE_INTEGER;
 
  // Iterate through the prime factors and check the
  // pairs that are possible.
  for (let p of prime_factors) {
    let to_be_added = p - (n % p);
    pairs = Math.min(pairs, to_be_added);
  }
 
  // Return the number of pairs
  return pairs;
}
 
// Function call
let n = 1;
let m = 4;
console.log(findMaxPairs(n, m));


Output

2

Time Complexity: O(NlogN ) where N is the size of the sieve.
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads