C++程序:查找给定数字根的范围内数字
数字根可以通过对其数字求和来找到;如果和是一个一位数,则它就是一个数字根。在本教程中,我们将讨论一个问题,其中给定一个数字范围和一个整数X,我们需要计算该范围内有多少个数字的数字根为X,其中X是一位数,例如
Input: l = 13, r = 25, X = 4 Output: 2 Explanation: Numbers in the range (13,25) having digit sum 4 are 13 and 22. Input: l = 11, r = 57 Output: 6
寻找解决方案的方法
简单方法
在简单的方法中,我们可以遍历从l到r的数字,并检查其和是否等于X。但这将产生O(N)的时间复杂度,其中N是范围内的总数。
高效方法
为了查找数字根为X的范围内的数字,我们需要检查范围内每个数字的数字之和是否等于K,而数字之和总是等于num % 9,如果余数为0,则为9。因此,如果X = 9,则将其更改为0。
为了找到数字的个数,我们将整个范围分成9组。然后,每组中恰好有一个数字的模9等于X。之后,检查不在组中的剩余数字;分别检查每个数字是否满足num % 9 = X的条件。
示例
上述方法的C++代码
#include <bits/stdc++.h> #define ll long long int using namespace std; int main(){ int l = 13; int r = 25; int X = 4; if (X == 9) X = 0; // count all the numbers in the range int total = r - l + 1; // Divide numbers into maximum groups of 9 int groups = total/ 9; // since for N groups there will be N numbers with modulo 9 equals to X. int result = groups; // check all the left out numbers int left_out = total % 9; // checking each left out number separately for the condition. for (int i = r; i > r - left_out; i--) { int rem = i % 9; if (rem == X) result++; } cout << "Total Numbers in a Range( l, r ) with given Digital Root(X) are: " << result; return 0; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
Total Numbers in a Range( l, r ) with given Digital Root(X) are: 2
结论
在本教程中,我们讨论了一个具有数字范围和数字根的问题。我们需要找到所有数字根为X的数字。我们讨论了一个简单的方法和一个高效的方法来解决这个问题,方法是将数字分成9位数的组。
每组包含一个数字根为X的数字。我们还讨论了这个问题的C++程序,我们可以使用C、Java、Python等编程语言来实现。我们希望您觉得本教程有所帮助。
广告