Wednesday, July 13, 2022
HomeWordPress DevelopmentVariety of distinct GCD by including identical quantity with given two integers

Variety of distinct GCD by including identical quantity with given two integers


View Dialogue

Enhance Article

Save Article

Like Article

Given two constructive integers N and M, the duty is to seek out the variety of completely different GCDs which may be fashioned by including an integer Ok to each N and M, the place Ok ≥ 0.

Examples:

Enter: N = 8, M = 4
Output: 3
Rationalization: If Ok = 0, then GCD(8, 4) = 4,
If Ok = 1, then GCD(9, 5) = 1,
If Ok = 2, then GCD(10, 6) = 2

Enter: N = 7, M = 10
Output: 2
Rationalization: If Ok = 0, then GCD(7, 10) = 1,
If Ok = 2, then GCD(9, 12) = 3

 

Method: The issue may be solved based mostly on the next mathematical thought:

The utmost worth of GCD fashioned after including any worth of Ok can be abs(N – M).
Aside from the above consequence if every other GCD is fashioned, that can be an ideal divisor of abs(N – M).

Comply with the steps under to implement the above thought:

  • Discover absolutely the distinction between N and M (say X).
  • Discover the variety of distinctive divisors of the X.
  • Return this worth because the required reply.

Beneath is the implementation of the above method:

Java

  

import java.util.*;

  

class GFG {

  

    

    public static void foremost(String[] args)

    {

        int N = 8;

        int M = 4;

  

        

        System.out.println(distinctGCDs(N, M));

    }

  

    

    

    public static int distinctGCDs(int N, int M)

    {

        

        

        Set<Integer> hs = new HashSet<>();

        int diff = Math.abs(N - M);

  

        

        

        for (int i = 1; i * i <= diff; i++) {

  

            

            

            if (diff % i == 0) {

                hs.add(i);

                hs.add(diff / i);

            }

        }

  

        

        

        return hs.measurement();

    }

}

Time Complexity: O(sqrt(abs(N – M)))
Auxiliary House: O(sqrt(abs(N – M)))

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments