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;
}

輸出

Total Numbers in a Range( l, r ) with given Digital Root(X) are: 2

結論

在本教程中,我們討論了一個具有數字範圍和數字根的問題。我們需要找到所有數字根為X的數字。我們討論了一個簡單的方法和一個高效的方法來解決這個問題,方法是將數字分成9位數的組。

每組包含一個數字根為X的數字。我們還討論了這個問題的C++程式,我們可以使用C、Java、Python等程式語言來實現。我們希望您覺得本教程有所幫助。

更新於:2021年11月25日

瀏覽量:177

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告