找到最大可被 X 整除的 K 位数
在这个题目中,我们将尝试找出最大的 K 位数,该数可以被 X 整除。为此,我们将使用此公式 ((10^k) – 1) 获取最大的 K 位数。然后检查该数是否可以被 X 整除,如果不是,我们将使用此公式获取确切的数。
𝑚𝑎𝑥−(𝑚𝑎𝑥 𝑚𝑜𝑑 𝑋)
一个示例像一个 5 位数,可以被 29 整除。因此,最大的 5 位数是 99999。这无法被 29 整除。现在通过应用公式,我们将得到 −
99999−(99999 𝑚𝑜𝑑 29)=99999−7=99992
该数字 99992 可以被 29 整除。
算法
maxKDigit(k, x)
begin max = (10^k) - 1 if max is divisible by x, return max otherwise return max – (max mod x) end
示例
#include<iostream>
#include<cmath>
using namespace std;
long max_k_digit(int k, int x){
//get the maximum number of k digits
int max = pow(10, k) - 1;
if(max % x == 0){
return max;
}
return (max) - (max % x);
}
main() {
int k, x;
cout << "Enter Digit Count(K) and Divisor(N): ";
cin >> k >> x;
cout << "Result is: " << max_k_digit(k, x);
}输出
Enter Digit Count(K) and Divisor(N): 5 29 Result is: 99992
输出
Enter Digit Count(K) and Divisor(N): 6 87 Result is: 999978
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP