logo

두 숫자의 공약수

두 개의 정수가 주어지면 주어진 숫자의 모든 공약수의 개수를 찾는 것이 과제입니다.

예:  

Input : a = 12 b = 24 Output: 6 // all common divisors are 1 2 3 // 4 6 and 12 Input : a = 3 b = 17 Output: 1 // all common divisors are 1 Input : a = 20 b = 36 Output: 3 // all common divisors are 1 2 4
Recommended Practice 공약수 시도해 보세요!

참고하는 것이 좋습니다 주어진 숫자의 모든 약수 이 기사의 전제 조건으로. 



순진한 솔루션  
간단한 해결책은 먼저 첫 번째 숫자의 모든 약수를 찾아 배열이나 해시에 저장하는 것입니다. 그런 다음 두 번째 숫자의 공약수를 찾아 저장합니다. 마지막으로 저장된 두 배열 또는 해시의 공통 요소를 인쇄합니다. 핵심은 제수의 소인수 거듭제곱의 크기가 a와 b의 두 소인수에 대한 최소 거듭제곱과 같아야 한다는 것입니다.

  • 사용의 주요 요인 찾기 소인수분해 .
  • 각 소인수 개수를 구합니다. 에이 그리고 해시맵에 저장합니다.
  • 소인수분해 서로 다른 소인수를 사용하여 에이 .
  • 그러면 총 제수 수는 다음의 곱과 같습니다. (개수 + 1) 
    각 요인의.
  • 세다는 각 소인수 개수의 최소값입니다. 에이 그리고 비.
  • 이것은 모든 제수의 개수를 제공합니다. 에이 그리고 .
C++
// C++ implementation of program  #include    using namespace std; // Map to store the count of each // prime factor of a  map<int int> ma; // Function that calculate the count of  // each prime factor of a number  void primeFactorize(int a)  {   for(int i = 2; i * i <= a; i += 2)   {   int cnt = 0;   while (a % i == 0)   {   cnt++;   a /= i;   }   ma[i] = cnt;   }   if (a > 1)  {  ma[a] = 1;  } }  // Function to calculate all common // divisors of two given numbers  // a b --> input integer numbers  int commDiv(int a int b)  {     // Find count of each prime factor of a   primeFactorize(a);   // stores number of common divisors   int res = 1;   // Find the count of prime factors   // of b using distinct prime factors of a   for(auto m = ma.begin();  m != ma.end(); m++)  {  int cnt = 0;   int key = m->first;   int value = m->second;   while (b % key == 0)   {   b /= key;   cnt++;   }   // Prime factor of common divisor   // has minimum cnt of both a and b   res *= (min(cnt value) + 1);   }   return res;  }  // Driver code  int main() {  int a = 12 b = 24;     cout << commDiv(a b) << endl;     return 0; } // This code is contributed by divyeshrabadiya07 
Java
// Java implementation of program import java.util.*; import java.io.*; class GFG {  // map to store the count of each prime factor of a  static HashMap<Integer Integer> ma = new HashMap<>();  // method that calculate the count of  // each prime factor of a number  static void primeFactorize(int a)  {  for (int i = 2; i * i <= a; i += 2) {  int cnt = 0;  while (a % i == 0) {  cnt++;  a /= i;  }  ma.put(i cnt);  }  if (a > 1)  ma.put(a 1);  }  // method to calculate all common divisors  // of two given numbers  // a b --> input integer numbers  static int commDiv(int a int b)  {  // Find count of each prime factor of a  primeFactorize(a);  // stores number of common divisors  int res = 1;  // Find the count of prime factors of b using  // distinct prime factors of a  for (Map.Entry<Integer Integer> m : ma.entrySet()) {  int cnt = 0;  int key = m.getKey();  int value = m.getValue();  while (b % key == 0) {  b /= key;  cnt++;  }  // prime factor of common divisor  // has minimum cnt of both a and b  res *= (Math.min(cnt value) + 1);  }  return res;  }  // Driver method  public static void main(String args[])  {  int a = 12 b = 24;  System.out.println(commDiv(a b));  } } 
Python3
# Python3 implementation of program  import math # Map to store the count of each # prime factor of a  ma = {} # Function that calculate the count of  # each prime factor of a number  def primeFactorize(a): sqt = int(math.sqrt(a)) for i in range(2 sqt 2): cnt = 0 while (a % i == 0): cnt += 1 a /= i ma[i] = cnt if (a > 1): ma[a] = 1 # Function to calculate all common # divisors of two given numbers  # a b --> input integer numbers  def commDiv(a b): # Find count of each prime factor of a  primeFactorize(a) # stores number of common divisors  res = 1 # Find the count of prime factors  # of b using distinct prime factors of a  for key value in ma.items(): cnt = 0 while (b % key == 0): b /= key cnt += 1 # Prime factor of common divisor  # has minimum cnt of both a and b  res *= (min(cnt value) + 1) return res # Driver code  a = 12 b = 24 print(commDiv(a b)) # This code is contributed by Stream_Cipher 
C#
// C# implementation of program using System; using System.Collections.Generic;  class GFG{   // Map to store the count of each  // prime factor of a static Dictionary<int  int> ma = new Dictionary<int  int>(); // Function that calculate the count of // each prime factor of a number static void primeFactorize(int a) {  for(int i = 2; i * i <= a; i += 2)  {  int cnt = 0;  while (a % i == 0)  {  cnt++;  a /= i;  }  ma.Add(i cnt);  }    if (a > 1)  ma.Add(a 1); } // Function to calculate all common  // divisors of two given numbers // a b --> input integer numbers static int commDiv(int a int b) {    // Find count of each prime factor of a  primeFactorize(a);    // Stores number of common divisors  int res = 1;    // Find the count of prime factors  // of b using distinct prime factors of a  foreach(KeyValuePair<int int> m in ma)  {  int cnt = 0;  int key = m.Key;  int value = m.Value;    while (b % key == 0)  {  b /= key;  cnt++;  }  // Prime factor of common divisor  // has minimum cnt of both a and b  res *= (Math.Min(cnt value) + 1);  }  return res; } // Driver code  static void Main() {  int a = 12 b = 24;    Console.WriteLine(commDiv(a b)); } } // This code is contributed by divyesh072019 
JavaScript
<script>   // JavaScript implementation of program  // Map to store the count of each  // prime factor of a  let ma = new Map();  // Function that calculate the count of  // each prime factor of a number  function primeFactorize(a)  {  for(let i = 2; i * i <= a; i += 2)  {  let cnt = 0;  while (a % i == 0)  {  cnt++;  a = parseInt(a / i 10);  }  ma.set(i cnt);  }  if (a > 1)  {  ma.set(a 1);  }  }  // Function to calculate all common  // divisors of two given numbers  // a b --> input integer numbers  function commDiv(ab)  {  // Find count of each prime factor of a  primeFactorize(a);  // stores number of common divisors  let res = 1;  // Find the count of prime factors  // of b using distinct prime factors of a  ma.forEach((valueskeys)=>{  let cnt = 0;  let key = keys;  let value = values;  while (b % key == 0)  {  b = parseInt(b / key 10);  cnt++;  }  // Prime factor of common divisor  // has minimum cnt of both a and b  res *= (Math.min(cnt value) + 1);  })  return res;  }  // Driver code  let a = 12 b = 24;    document.write(commDiv(a b));   </script> 

산출:  

6

시간 복잡도 : O(?n log n) 
보조 공간: 에)


효율적인 솔루션 - 
더 나은 해결책은 다음을 계산하는 것입니다. 최대 공약수(gcd) 주어진 두 숫자의 수를 계산하고 그 gcd의 제수를 셉니다. 

C++
// C++ implementation of program #include    using namespace std; // Function to calculate gcd of two numbers int gcd(int a int b) {  if (a == 0)  return b;  return gcd(b % a a); } // Function to calculate all common divisors // of two given numbers // a b --> input integer numbers int commDiv(int a int b) {  // find gcd of a b  int n = gcd(a b);  // Count divisors of n.  int result = 0;  for (int i = 1; i <= sqrt(n); i++) {  // if 'i' is factor of n  if (n % i == 0) {  // check if divisors are equal  if (n / i == i)  result += 1;  else  result += 2;  }  }  return result; } // Driver program to run the case int main() {  int a = 12 b = 24;  cout << commDiv(a b);  return 0; } 
Java
// Java implementation of program class Test {  // method to calculate gcd of two numbers  static int gcd(int a int b)  {  if (a == 0)  return b;  return gcd(b % a a);  }  // method to calculate all common divisors  // of two given numbers  // a b --> input integer numbers  static int commDiv(int a int b)  {  // find gcd of a b  int n = gcd(a b);  // Count divisors of n.  int result = 0;  for (int i = 1; i <= Math.sqrt(n); i++) {  // if 'i' is factor of n  if (n % i == 0) {  // check if divisors are equal  if (n / i == i)  result += 1;  else  result += 2;  }  }  return result;  }  // Driver method  public static void main(String args[])  {  int a = 12 b = 24;  System.out.println(commDiv(a b));  } } 
Python3
# Python implementation of program from math import sqrt # Function to calculate gcd of two numbers def gcd(a b): if a == 0: return b return gcd(b % a a) # Function to calculate all common divisors  # of two given numbers  # a b --> input integer numbers  def commDiv(a b): # find GCD of a b n = gcd(a b) # Count divisors of n result = 0 for i in range(1int(sqrt(n))+1): # if i is a factor of n if n % i == 0: # check if divisors are equal if n/i == i: result += 1 else: result += 2 return result # Driver program to run the case  if __name__ == '__main__': a = 12 b = 24; print(commDiv(a b)) 
C#
// C# implementation of program using System; class GFG {  // method to calculate gcd  // of two numbers  static int gcd(int a int b)  {  if (a == 0)  return b;  return gcd(b % a a);  }  // method to calculate all  // common divisors of two  // given numbers a b -->  // input integer numbers  static int commDiv(int a int b)  {  // find gcd of a b  int n = gcd(a b);  // Count divisors of n.  int result = 0;  for (int i = 1; i <= Math.Sqrt(n); i++) {  // if 'i' is factor of n  if (n % i == 0) {  // check if divisors are equal  if (n / i == i)  result += 1;  else  result += 2;  }  }  return result;  }  // Driver method  public static void Main(String[] args)  {  int a = 12 b = 24;  Console.Write(commDiv(a b));  } } // This code contributed by parashar. 
PHP
 // PHP implementation of program // Function to calculate  // gcd of two numbers function gcd($a $b) { if ($a == 0) return $b; return gcd($b % $a $a); } // Function to calculate all common  // divisors of two given numbers // a b --> input integer numbers function commDiv($a $b) { // find gcd of a b $n = gcd($a $b); // Count divisors of n. $result = 0; for ($i = 1; $i <= sqrt($n); $i++) { // if 'i' is factor of n if ($n % $i == 0) { // check if divisors  // are equal if ($n / $i == $i) $result += 1; else $result += 2; } } return $result; } // Driver Code $a = 12; $b = 24; echo(commDiv($a $b)); // This code is contributed by Ajit. ?> 
JavaScript
<script>  // Javascript implementation of program    // Function to calculate gcd of two numbers  function gcd(a b)  {  if (a == 0)  return b;  return gcd(b % a a);  }  // Function to calculate all common divisors  // of two given numbers  // a b --> input integer numbers  function commDiv(a b)  {  // find gcd of a b  let n = gcd(a b);  // Count divisors of n.  let result = 0;  for (let i = 1; i <= Math.sqrt(n); i++) {  // if 'i' is factor of n  if (n % i == 0) {  // check if divisors are equal  if (n / i == i)  result += 1;  else  result += 2;  }  }  return result;  }  let a = 12 b = 24;  document.write(commDiv(a b));   </script> 

출력 :   

6

시간 복잡도:1/2) 여기서 n은 두 숫자의 gcd입니다.
보조 공간: 오(1)

또 다른 접근법:

1. 두 개의 정수 'a'와 'b'를 취하고 유클리드 알고리즘을 사용하여 최대 공약수(GCD)를 반환하는 함수 'gcd'를 정의합니다.
2. 두 개의 정수 'a'와 'b'를 취하고 GCD를 사용하여 'a'와 'b'의 공약수의 수를 계산하는 'count_common_divisors' 함수를 정의합니다.
3. 'gcd' 함수를 사용하여 'a'와 'b'의 GCD를 계산합니다.
4. 카운터 'count'를 0으로 초기화합니다.
5. 'a'와 'b'의 GCD의 가능한 모든 제수를 1부터 GCD의 제곱근까지 반복합니다.
6. 현재 제수가 GCD를 균등하게 나누면 카운터를 2만큼 증가시킵니다('a'와 'b' 모두 제수로 나눌 수 있기 때문입니다).
7. 현재 제수의 제곱이 GCD와 같으면 카운터를 1만큼 감소시킵니다(이미 제수를 한 번 계산했기 때문입니다).
8. 공약수의 최종 개수를 반환합니다.
9. 메인 함수에서 두 개의 정수 'a'와 'b'를 정의하고 이 정수를 사용하여 'count_common_divisors' 함수를 호출합니다.
10. printf 함수를 사용하여 'a'와 'b'의 공약수의 수를 인쇄합니다.

C
#include  int gcd(int a int b) {  if(b == 0) {  return a;  }  return gcd(b a % b); } int count_common_divisors(int a int b) {  int gcd_ab = gcd(a b);  int count = 0;  for(int i = 1; i * i <= gcd_ab; i++) {  if(gcd_ab % i == 0) {  count += 2;  if(i * i == gcd_ab) {  count--;  }  }  }  return count; } int main() {  int a = 12;  int b = 18;  int common_divisors = count_common_divisors(a b);  printf('The number of common divisors of %d and %d is %d.n' a b common_divisors);  return 0; } 
C++
#include    using namespace std; int gcd(int a int b) {  if(b == 0) {  return a;  }  return gcd(b a % b); } int count_common_divisors(int a int b) {  int gcd_ab = gcd(a b);  int count = 0;  for(int i = 1; i * i <= gcd_ab; i++) {  if(gcd_ab % i == 0) {  count += 2;  if(i * i == gcd_ab) {  count--;  }  }  }  return count; } int main() {  int a = 12;  int b = 18;  int common_divisors = count_common_divisors(a b);  cout<<'The number of common divisors of '<<a<<' and '<<b<<' is '<<common_divisors<<'.'<<endl;  return 0; } 
Java
import java.util.*; public class Main {  public static int gcd(int a int b) {  if(b == 0) {  return a;  }  return gcd(b a % b);  }  public static int countCommonDivisors(int a int b) {  int gcd_ab = gcd(a b);  int count = 0;  for(int i = 1; i * i <= gcd_ab; i++) {  if(gcd_ab % i == 0) {  count += 2;  if(i * i == gcd_ab) {  count--;  }  }  }  return count;  }  public static void main(String[] args) {  int a = 12;  int b = 18;  int commonDivisors = countCommonDivisors(a b);  System.out.println('The number of common divisors of ' + a + ' and ' + b + ' is ' + commonDivisors + '.');  } } 
Python3
import math def gcd(a b): if b == 0: return a return gcd(b a % b) def count_common_divisors(a b): gcd_ab = gcd(a b) count = 0 for i in range(1 int(math.sqrt(gcd_ab)) + 1): if gcd_ab % i == 0: count += 2 if i * i == gcd_ab: count -= 1 return count a = 12 b = 18 common_divisors = count_common_divisors(a b) print('The number of common divisors of' a 'and' b 'is' common_divisors '.') # This code is contributed by Prajwal Kandekar 
C#
using System; public class MainClass {  public static int GCD(int a int b)  {  if (b == 0)  {  return a;  }  return GCD(b a % b);  }  public static int CountCommonDivisors(int a int b)  {  int gcd_ab = GCD(a b);  int count = 0;  for (int i = 1; i * i <= gcd_ab; i++)  {  if (gcd_ab % i == 0)  {  count += 2;  if (i * i == gcd_ab)  {  count--;  }  }  }  return count;  }  public static void Main()  {  int a = 12;  int b = 18;  int commonDivisors = CountCommonDivisors(a b);  Console.WriteLine('The number of common divisors of {0} and {1} is {2}.' a b commonDivisors);  } } 
JavaScript
// Function to calculate the greatest common divisor of  // two integers a and b using the Euclidean algorithm function gcd(a b) {  if(b === 0) {  return a;  }  return gcd(b a % b); } // Function to count the number of common divisors of two integers a and b function count_common_divisors(a b) {  let gcd_ab = gcd(a b);  let count = 0;  for(let i = 1; i * i <= gcd_ab; i++) {  if(gcd_ab % i === 0) {  count += 2;  if(i * i === gcd_ab) {  count--;  }  }  }  return count; } let a = 12; let b = 18; let common_divisors = count_common_divisors(a b); console.log(`The number of common divisors of ${a} and ${b} is ${common_divisors}.`); 

산출
The number of common divisors of 12 and 18 is 4.

gcd() 함수의 시간 복잡도는 두 숫자 중 더 작은 숫자에 대해 로그 시간이 걸리는 Euclid 알고리즘을 사용하므로 O(log(min(ab)))입니다.

count_common_divisors() 함수의 시간 복잡도는 두 숫자의 gcd의 제곱근까지 반복되므로 O(sqrt(gcd(ab)))입니다.

두 함수 모두 입력 크기에 관계없이 일정한 양의 메모리만 사용하므로 공간 복잡도는 O(1)입니다.