📌  相关文章
📜  从给定的两位数字组成的从1到N的互质对数

📅  最后修改于: 2021-04-17 16:00:39             🧑  作者: Mango

给定整数N 以及两个整数D1D2 ( <10 ),任务是找到小于或等于N的仅由数字D1D2组成的互质对数。

例子:

方法:解决此问题的想法是基于以下观察结果:

请按照以下步骤解决问题:

  • 初始化一个空列表,说l 并将给定的两位数字附加为 列表中的一个字符串。
  • 排序列表。
  • 初始化两个列表,例如totaltemp2,以供进一步使用。
  • 迭代直到l [0] <10:
    • 将给定的两位数字作为字符串附加到列表l中存在的所有元素
    • 按照以下所示的方式继续更新l
      • [2,3]-> [‘2’+’2’,’2’+’3’,’3’+’2’,’3’+’3’]
      • [22,23,32,33] –> [’22’+’2’,’22’+’3’,’23’+’2’,’23’+’3’,’32’+’2 ‘,’32’+’3’,’33’+’2’,’33’+’3’]等。
  • 定义一个函数numOfPairs() ,该函数返回无序互质对数的计数。
  • 打印以上函数返回的计数作为答案。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to check whether given
// integers are co-prime or not
int coprime(int a, int b) { return (__gcd(a, b) == 1); }
 
// Utility function to count
// number of co-prime pairs
int numOfPairs(vector arr, int N)
{
    int count = 0;
 
    // Traverse the array
    for (int i = 0; i < N - 1; i++) {
        for (int j = i + 1; j < N; j++) {
 
            // If co-prime
            if (coprime(stoi(arr[i]), stoi(arr[j]))) {
 
                // Increment count
                count = count + 1;
            }
        }
    }
    // Return count
    return count;
}
 
// Function to count number
// of co-prime pairs
int noOfCoPrimePairs(int N, int d1, int d2)
{
 
    // Stores digits in string form
    vector l;
    l.push_back(to_string(d1));
    l.push_back(to_string(d2));
 
    // Sort the list
    sort(l.begin(), l.end());
 
    if (N < stoi(l[1]))
        return 0;
 
    // Keep two copies of list l
    vector total = l;
    vector temp2 = l;
    int flag = 0;
    vector temp3;
 
    // Generate 2 digit numbers
    // using d1 and d2
    while (l[0].length() < 10) {
        for (int i = 0; i < l.size(); i++) {
            for (int j = 0; j < 2; j++) {
 
                // If current number
                // does not exceed N
                if (stoi(l[i] + temp2[j]) > N) {
                    flag = 1;
                    break;
                }
                total.push_back(l[i] + temp2[j]);
                temp3.push_back(l[i] + temp2[j]);
            }
            if (flag == 1)
                break;
        }
        if (flag == 1)
            break;
        l = temp3;
        vector temp3;
    }
 
    // Stores length of list
    int lenOfTotal = total.size();
 
    // Stores number of co-prime pairs
    int ans = numOfPairs(total, lenOfTotal);
 
    // Print number of co-prime pairs
    cout << (ans);
}
 
// Driver Code
int main()
{
 
    // Given value of N, d1, d2
    int N = 30, d1 = 2, d2 = 3;
 
    // Function call to count
    // number of co-prime pairs
    noOfCoPrimePairs(N, d1, d2);
}
 
// This code is contributed by ukasp.


Java
// Java program for the above approach
import java.util.*;       
 
class GFG{
   
static int GCD(int a, int b)
{
    return b == 0 ? a : GCD(b, a % b);
}
 
// Function to check whether given
// integers are co-prime or not
static boolean coprime(int a, int b)
{
    if (GCD(a, b) == 1)
        return true;
         
    return false;
}
 
// Utility function to count
// number of co-prime pairs
static int numOfPairs(ArrayList arr, int N)
{
    int count = 0;
 
    // Traverse the array
    for(int i = 0; i < N - 1; i++)
    {
        for(int j = i + 1; j < N; j++)
        {
             
            // If co-prime
            if (coprime(Integer.parseInt(arr.get(i)),
                        Integer.parseInt(arr.get(j))))
            {
                 
                // Increment count
                count = count + 1;
            }
        }
    }
     
    // Return count
    return count;
}
 
// Function to count number
// of co-prime pairs
static void noOfCoPrimePairs(int N, int d1, int d2)
{
     
    // Stores digits in string form
    ArrayList l = new ArrayList();  
    l.add(Integer.toString(d1));
    l.add(Integer.toString(d2));
 
    // Sort the list
    Collections.sort(l);
     
    if (N < Integer.parseInt(l.get(1)))
        return;
 
    // Keep two copies of list l
    ArrayList total = new ArrayList(l);  
    ArrayList temp2 = new ArrayList(l);  
    int flag = 0;
    ArrayList temp3 = new ArrayList(l); 
     
    // Generate 2 digit numbers
    // using d1 and d2
    while (l.get(0).length() < 10)
    {
        for(int i = 0; i < l.size(); i++)
        {
            for(int j = 0; j < 2; j++)
            {
                 
                // If current number
                // does not exceed N
                if (Integer.parseInt(l.get(i) +
                                 temp2.get(j)) > N)
                {
                    flag = 1;
                    break;
                }
                total.add(l.get(i) + temp2.get(j));
                temp3.add(l.get(i) + temp2.get(j));
            }
            if (flag == 1)
                break;
        }
        if (flag == 1)
            break;
             
        l = temp3;
        temp3.clear();
    }
 
    // Stores length of list
    int lenOfTotal = total.size();
 
    // Stores number of co-prime pairs
    int ans = numOfPairs(total, lenOfTotal);
 
    // Print number of co-prime pairs
    System.out.print(ans);
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given value of N, d1, d2
    int N = 30, d1 = 2, d2 = 3;
 
    // Function call to count
    // number of co-prime pairs
    noOfCoPrimePairs(N, d1, d2);
}
}
 
// This code is contributed by bgangwar59


Python3
# Python3 program for the above approach
 
from copy import deepcopy
import math
 
# Function to check whether given
# integers are co-prime or not
def coprime(a, b):
    return (math.gcd(a, b)) == 1
 
# Utility function to count
# number of co-prime pairs
def numOfPairs(arr, N):
    count = 0
 
    # Traverse the array
    for i in range(0, N-1):
        for j in range(i+1, N):
 
            # If co-prime
            if (coprime(int(arr[i]), int(arr[j]))):
 
                # Increment count
                count = count + 1
 
    # Return count
    return count
 
# Function to count number
# of co-prime pairs
def noOfCoPrimePairs(N, d1, d2):
 
    # Stores digits in string form
    l = []
    l.append(str(d1))
    l.append(str(d2))
 
    # Sort the list
    l.sort()
 
    if int(N) < int(l[1]):
        return 0
 
    # Keep two copies of list l
    total = temp2 = deepcopy(l)
    flag = 0
    temp3 = []
 
    # Generate 2 digit numbers
    # using d1 and d2
    while len(l[0]) < 10:
        for i in range(len(l)):
            for j in range(2):
 
                # If current number
                # does not exceed N
                if int(l[i]+temp2[j]) > int(N):
                    flag = 1
                    break
 
                total.append(l[i]+temp2[j])
                temp3.append(l[i]+temp2[j])
 
            if flag == 1:
                break
        if flag == 1:
            break
        l = deepcopy(temp3)
        temp3 = []
 
    # Stores length of list
    lenOfTotal = len(total)
 
    # Stores number of co-prime pairs
    ans = numOfPairs(total, lenOfTotal)
 
    # Print number of co-prime pairs
    print(ans)
 
 
# Driver Code
if __name__ == "__main__":
 
    # Given value of N, d1, d2
    N = 30
    d1 = 2
    d2 = 3
 
    # Function call to count
    # number of co-prime pairs
    noOfCoPrimePairs(N, d1, d2)


C#
// C# program for the above approach
using System;
using System.Collections.Generic;       
 
class GFG{
   
static int GCD(int a, int b)
{
    return b == 0 ? a : GCD(b, a % b);
}
 
// Function to check whether given
// integers are co-prime or not
static bool coprime(int a, int b)
{
    if (GCD(a, b) == 1)
        return true;
         
    return false;
}
 
// Utility function to count
// number of co-prime pairs
static int numOfPairs(List arr, int N)
{
    int count = 0;
 
    // Traverse the array
    for(int i = 0; i < N - 1; i++)
    {
        for(int j = i + 1; j < N; j++)
        {
             
            // If co-prime
            if (coprime(Int32.Parse(arr[i]),
                        Int32.Parse(arr[j])))
            {
                 
                // Increment count
                count = count + 1;
            }
        }
    }
     
    // Return count
    return count;
}
 
// Function to count number
// of co-prime pairs
static void noOfCoPrimePairs(int N, int d1, int d2)
{
     
    // Stores digits in string form
    List l = new List();
    l.Add(d1.ToString());
    l.Add(d2.ToString());
 
    // Sort the list
    l.Sort();
     
    if (N < Int32.Parse(l[1]))
        return;
 
    // Keep two copies of list l
    List total = new List(l);
    List temp2 = new List(l);
    int flag = 0;
    List temp3 = new List();
     
    // Generate 2 digit numbers
    // using d1 and d2
    while (l[0].Length < 10)
    {
        for(int i = 0; i < l.Count; i++)
        {
            for(int j = 0; j < 2; j++)
            {
                 
                // If current number
                // does not exceed N
                if (Int32.Parse(l[i] + temp2[j]) > N)
                {
                    flag = 1;
                    break;
                }
                total.Add(l[i] + temp2[j]);
                temp3.Add(l[i] + temp2[j]);
            }
            if (flag == 1)
                break;
        }
        if (flag == 1)
            break;
             
        l = temp3;
        temp3.Clear();
    }
 
    // Stores length of list
    int lenOfTotal = total.Count;
 
    // Stores number of co-prime pairs
    int ans = numOfPairs(total, lenOfTotal);
 
    // Print number of co-prime pairs
    Console.WriteLine(ans);
}
 
// Driver Code
public static void Main()
{
     
    // Given value of N, d1, d2
    int N = 30, d1 = 2, d2 = 3;
 
    // Function call to count
    // number of co-prime pairs
    noOfCoPrimePairs(N, d1, d2);
}
}
 
// This code is contributed by ipg2016107


输出:
5

时间复杂度: O(2 logN )
辅助空间: O(2 logN )