C++中計算區間內能被m整除且偶數位包含數字d的數字個數
給定一個整數區間、一個用作除數的變數m和一個用於檢查數字'd'是否位於偶數位的變數d,任務是計算區間內能被變數m整除且偶數位包含數字d的數字個數。
例如
輸入 - int start = 20, end = 50, d = 8, m = 4
輸出 - 區間內能被m整除且偶數位包含數字d的數字個數為:2
解釋 - 區間從20到50。因此,包含數字d(即8)的可能數字是28、38和48,其中8位於偶數位(即第2位),數字24和48能被m(即4)整除,因此個數為2。
輸入 - int start = 10, end = 100, d = 6, m = 2
輸出 - 區間內能被m整除且偶數位包含數字d的數字個數為:8
解釋 - 區間從10到100。因此,包含數字d(即6)的可能數字是16、26、36、46、56、66、76、86和96,其中6位於偶數位,除了6和66(6位於奇數位),我們不包含這些數字。現在,我們將檢查列表中能被2整除的數字,因此所有數字(即16、26、36、46、56、76、86和96)都能被2整除,因此個數為8。
下面程式中使用的演算法如下
- 建立一個從變數start到變數end的整數數字範圍,並宣告變數d和m並輸入值。將資料傳遞給函式以進行進一步處理。
- 建立一個向量型別的變數,例如vec。
- 啟動while迴圈,直到值為變數start中的值。現在,在while迴圈內部,將值val % 10壓入向量中,並將val設定為val / 10。
- 透過傳遞vec.begin()和vec.end()作為引數,呼叫STL中的reverse函式。
- 使用memset將陣列中的值設定為-1。
- 返回set_total(0, 0, 0, vec),這是一個將檢查數字的偶數位是否為d且能被m整除的函式。
- 在set_total函式內部 -
- 檢查IF place等於向量的size,然後檢查IF temp = 0,則返回1或返回0。
- 檢查IF arr[place][temp][val]不等於-1,則返回arr[place][temp][val]的值。
- 檢查IF place % 2 = 1,則檢查IF val = 0,則檢查IF d大於vec[place],則返回0
- 宣告變數temp_2並將其設定為0。
- 檢查IF d小於vec[place],則將temp_2設定為1。
- 宣告變數temp_3並遞迴呼叫set_total(),並返回arr[place][temp][val] = temp_3
- 宣告一個變數count來儲存結果。
- 宣告一個變數set_limit,如果val等於1,則將其設定為9,否則將其設定為vec[place]。
- 從i = 0開始迴圈到set_limit,並檢查IF i等於d,則繼續。
- 宣告一個變數temp_2並將其設定為val
- 檢查IF i小於vec[place],則將temp_2設定為1
- 使用對set_total函式的遞迴呼叫設定count
- 返回arr[place][temp][val] = count。
示例
#include <bits/stdc++.h> using namespace std; int arr[20][20][2]; int d, m; int set_total(int place, int temp, int val, vector < int > vec) { if (place == vec.size()) { if (temp == 0) { return 1; } return 0; } if (arr[place][temp][val] != -1) { return arr[place][temp][val]; } if (place % 2) { if (val == 0) { if (d > vec[place]) { return 0; } } int temp_2 = val; if (d < vec[place]) { temp_2 = 1; } int temp_3 = set_total(place + 1, (10 * temp + d) % m, temp_2, vec); return arr[place][temp][val] = temp_3; } int count = 0; int set_limit = (val ? 9 : vec[place]); for (int i = 0; i <= set_limit; i++) { if (i == d) { continue; } int temp_2 = val; if (i < vec[place]) { temp_2 = 1; } count += set_total(place + 1, (10 * temp + i) % m, temp_2, vec); } return arr[place][temp][val] = count; } int divisible(int val) { vector < int > vec; while (val) { vec.push_back(val % 10); val = val / 10; } reverse(vec.begin(), vec.end()); memset(arr, -1, sizeof(arr)); return set_total(0, 0, 0, vec); } int main() { int start = 20, end = 50; d = 8, m = 4; int count = divisible(end) - divisible(start); cout << "Count of Numbers in a Range divisible by m and having digit d in even positions are: " << count; return 0; }
如果我們執行上述程式碼,它將生成以下輸出:
輸出
Count of Numbers in a Range divisible by m and having digit d in even positions are: 2
廣告