📜  计算相邻数字具有相等 GCD 的 N 位数字

📅  最后修改于: 2021-09-22 09:40:37             🧑  作者: Mango

给定一个正整数N ,任务是找到所有相邻数字具有相等最大公约数(GCD)的N位数字的个数。

例子:

朴素方法:解决给定问题的最简单方法是生成所有可能的N位数字,并计算相邻数字具有相同 GCD 的那些数字。检查所有数字后,打印计数值作为结果的总数字计数。

时间复杂度: O(N *10 N )
辅助空间: O(1)

高效方法:上述方法也可以使用动态规划进行优化,因为上述问题具有重叠子问题和最优子结构。子问题可以存储在dp[][][] 表记忆中,其中dp[index][prev][gcd]存储从索引第 th位置到末尾的答案,其中prev用于存储数字的前一位gcd是数字中现有相邻数字之间的 GCD。请按照以下步骤解决问题:

  • 初始化一个全局多维数组dp[100][10][10] ,所有值都为-1 ,用于存储每个递归调用的结果。
  • 定义一个递归函数,比如countOfNumbers(index, prev, gcd, N)并执行以下步骤:
    • 如果索引的值为(N + 1) ,则返回1作为有效的N位数字已形成。
    • 如果已经计算了状态dp[index][prev][gcd] 的结果,则返回此值dp[index][prev][gcd]
    • 如果当前索引1 ,则可以放置[1-9] 中的任何数字。
    • 如果当前索引大于1 ,则可以放置[0-9] 中的任何数字。
    • 如果索引大于2 ,如果当前数字和前一个数字的 gcd 等于已经存在的相邻数字的 GCD,则可以放置一个数字。
    • 在有效放置数字后,递归调用(index + 1)countOfNumbers函数。
    • 返回所有可能的有效数字位置的总和作为答案。
  • 打印函数countOfNumbers(1, 0, 0, N)返回的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
int dp[100][10][10];
 
// Recursive function to find the count
// of all the N-digit numbers whose
// adjacent digits having equal GCD
int countOfNumbers(int index, int prev,
                   int gcd, int N)
{
    // If index is N+1
    if (index == N + 1)
        return 1;
 
    int& val = dp[index][prev][gcd];
 
    // If the state has already
    // been computed
    if (val != -1)
        return val;
 
    // Stores the total count of all
    // N-digit numbers
    val = 0;
 
    // If index = 1, any digit from
    // [1-9] can be placed.
 
    // If N = 0, 0 can be placed as well
    if (index == 1) {
 
        for (int digit = (N == 1 ? 0 : 1);
             digit <= 9;
             ++digit) {
 
            // Update the value val
            val += countOfNumbers(
                index + 1,
                digit, gcd, N);
        }
    }
 
    // If index is 2, then any digit
    // from [0-9] can be placed
    else if (index == 2) {
 
        for (int digit = 0;
             digit <= 9; ++digit) {
            val += countOfNumbers(
                index + 1, digit,
                __gcd(prev, digit), N);
        }
    }
 
    // Otherwise any digit from [0-9] can
    // be placed if the GCD of current
    // and previous digit is gcd
    else {
 
        for (int digit = 0;
             digit <= 9; ++digit) {
 
            // Check if GCD of current
            // and previous digit is gcd
            if (__gcd(digit, prev) == gcd) {
                val += countOfNumbers(
                    index + 1, digit, gcd, N);
            }
        }
    }
 
    // Return the total count
    return val;
}
 
// Function to find the count of all
// the N-digit numbers whose adjacent
// digits having equal GCD
int countNumbers(int N)
{
    // Initialize dp array with -1
    memset(dp, -1, sizeof dp);
 
    // Function Call to find the
    // resultant count
    return countOfNumbers(1, 0, 0, N);
}
 
// Driver Code
int main()
{
    int N = 2;
    cout << countNumbers(N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG
{
static int[][][] dp = new int[100][10][10];
 
static int _gcd(int a, int b)
    {
        // Everything divides 0
        if (a == 0)
          return b;
        if (b == 0)
          return a;
       
        // base case
        if (a == b)
            return a;
       
        // a is greater
        if (a > b)
            return _gcd(a-b, b);
        return _gcd(a, b-a);
    }
 
// Recursive function to find the count
// of all the N-digit numbers whose
// adjacent digits having equal GCD
static int countOfNumbers(int index, int prev,
                   int gcd, int N)
{
    // If index is N+1
    if (index == N + 1)
        return 1;
 
    int val = dp[index][prev][gcd];
 
    // If the state has already
    // been computed
    if (val != -1)
        return val;
 
    // Stores the total count of all
    // N-digit numbers
    val = 0;
 
    // If index = 1, any digit from
    // [1-9] can be placed.
 
    // If N = 0, 0 can be placed as well
    if (index == 1) {
 
        for (int digit = (N == 1 ? 0 : 1);
             digit <= 9;
             ++digit) {
 
            // Update the value val
            val += countOfNumbers(
                index + 1,
                digit, gcd, N);
        }
    }
 
    // If index is 2, then any digit
    // from [0-9] can be placed
    else if (index == 2) {
 
        for (int digit = 0;
             digit <= 9; ++digit) {
            val += countOfNumbers(
                index + 1, digit,
                _gcd(prev, digit), N);
        }
    }
 
    // Otherwise any digit from [0-9] can
    // be placed if the GCD of current
    // and previous digit is gcd
    else {
 
        for (int digit = 0;
             digit <= 9; ++digit) {
 
            // Check if GCD of current
            // and previous digit is gcd
            if (_gcd(digit, prev) == gcd) {
                val += countOfNumbers(
                    index + 1, digit, gcd, N);
            }
        }
    }
 
    // Return the total count
    return val;
}
 
// Function to find the count of all
// the N-digit numbers whose adjacent
// digits having equal GCD
static int countNumbers(int N)
{
    int i, j, k;
   
    // Initialize dp array with -1
    for(i = 0; i < 100; i++)
    {
        for(j = 0; j < 10; j++)
        {
            for(k = 0; k < 10; k++)
            {
                dp[i][j][k] = -1;
            }
        }
    }
     
    // Function Call to find the
    // resultant count
    return countOfNumbers(1, 0, 0, N);
}
 
    public static void main(String[] args)
    {
        int N = 2;
    System.out.println(countNumbers(N));
    }
}
 
// This code is contributed by target_2


Python3
# Python3 program for the above approach
dp = [[[-1 for i in range(10)]
           for j in range(10)]
           for k in range(100)]
 
from math import gcd
 
# Recursive function to find the count
# of all the N-digit numbers whose
# adjacent digits having equal GCD
def countOfNumbers(index, prev, gcd1, N):
     
    # If index is N+1
    if (index == N + 1):
        return 1
 
    val = dp[index][prev][gcd1]
 
    # If the state has already
    # been computed
    if (val != -1):
        return val
 
    # Stores the total count of all
    # N-digit numbers
    val = 0
 
    # If index = 1, any digit from
    # [1-9] can be placed.
 
    # If N = 0, 0 can be placed as well
    if (index == 1):
        digit = 0 if N == 1 else 1
         
        while(digit <= 9):
             
            # Update the value val
            val += countOfNumbers(index + 1,
                                  digit, gcd1, N)
            digit += 1
 
    # If index is 2, then any digit
    # from [0-9] can be placed
    elif (index == 2):
        for digit in range(10):
            val += countOfNumbers(index + 1, digit,
                                  gcd(prev, digit), N)
 
    # Otherwise any digit from [0-9] can
    # be placed if the GCD of current
    # and previous digit is gcd
    else:
        for digit in range(10):
             
            # Check if GCD of current
            # and previous digit is gcd
            if (gcd(digit, prev) == gcd):
                val += countOfNumbers(index + 1, digit,
                                      gcd1, N)
 
    # Return the total count
    return val
 
# Function to find the count of all
# the N-digit numbers whose adjacent
# digits having equal GCD
def countNumbers(N):
     
    # Function Call to find the
    # resultant count
    return countOfNumbers(1, 0, 0, N)
 
# Driver Code
if __name__ == '__main__':
     
    N = 2
    print(countNumbers(N))
 
 
# This code is contributed by ipg2016107


Javascript


输出:
90

时间复杂度: O(N * 1000)
辅助空间: O(N * 10 * 10)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程