可被 M 整除的第 K 个最大的 N 位数
给定三个正整数N 、 K和M 。任务是找到可被M整除的第K个最大的N位数。
注意: K 将是这样一个整数,即始终存在可被M整除的第 K个最大的N位数。
例子
Input: N = 2, K = 2, M = 2
Output: 96
Explanation: The 2nd largest 2 digit number divisible by 2 is 96.
Input: N = 9, K = 6, M = 4
Output: 999999976
方法:问题是基于数学的。给定三个数字N 、 K和M 。需要找到可被M整除的第K个最大的N位数。要获得可被M整除的最大N位数,首先需要找到最大的N位数(例如P ),即N乘以9 。
现在可被M整除的最大N位数是(P – (P%M)) 。
因此,从该值中减去 (K-1) 次 M以得到可被M整除的N位数的第 K个最大值。
下面给出了获得可被M整除的第 K个最大N位数的条件和数学表达式。
Let P be the largest N digit number.
Then the largest N digit number divisible by M is: (P – (P % M)).
Now the Kth largest N digit number divisible by M is: [(P – (P % M)) – ((K – 1) * M)]
下面是根据上述公式的代码。
C++
// C++ program for above approach
#include
using namespace std;
// Function to find Kth N
// digit number divisible by M
int findAnswer(int N, int K, int M)
{
int i;
long long int r = 0;
// Loop to calculate the largest
// N digit number.
for (i = 1; i <= N; i++) {
r = r * 10 + 9;
}
// Kth largest N digit number
// divisible by M.
long long int u = r - (r % M)
- M * (K - 1);
return u;
}
// Driver Code
int main()
{
int N = 9;
int K = 6;
int M = 4;
cout << findAnswer(N, K, M);
return 0;
}
Java
// Java program for above approach
import java.util.*;
class GFG{
// Function to find Kth N
// digit number divisible by M
static int findAnswer(int N, int K, int M)
{
int i;
int r = 0;
// Loop to calculate the largest
// N digit number.
for (i = 1; i <= N; i++) {
r = r * 10 + 9;
}
// Kth largest N digit number
// divisible by M.
int u = r - (r % M)
- M * (K - 1);
return u;
}
// Driver Code
public static void main(String[] args)
{
int N = 9;
int K = 6;
int M = 4;
System.out.print(findAnswer(N, K, M));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python code for the above approach
# Function to find Kth N
# digit number divisible by M
def findAnswer(N, K, M):
i = None
r = 0;
# Loop to calculate the largest
# N digit number.
for i in range(1, N + 1):
r = r * 10 + 9;
# Kth largest N digit number
# divisible by M.
u = r - (r % M) - M * (K - 1);
return u;
# Driver Code
N = 9;
K = 6;
M = 4;
print(findAnswer(N, K, M));
# This code is contributed by Saurabh Jaiswal
C#
// C# program for above approach
using System;
class GFG
{
// Function to find Kth N
// digit number divisible by M
static int findAnswer(int N, int K, int M)
{
long r = 0;
// Loop to calculate the largest
// N digit number.
for (int i = 1; i <= N; i++) {
r = r * 10 + 9;
}
// Kth largest N digit number
// divisible by M.
long u = r - (r % M)
- M * (K - 1);
return (int)u;
}
// Driver Code
public static void Main()
{
int N = 9;
int K = 6;
int M = 4;
Console.Write(findAnswer(N, K, M));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
999999976
时间复杂度: O(MaxDigit),其中 maxDigit 是最大的 N 位数。
辅助空间: O(1)