มีตัวเลข n และค่า เราต้องหาตัวเลข n หลักทั้งหมด โดยที่ผลรวมของ n หลักทั้งหมด s จะเหมือนกับค่าที่กำหนด ที่นี่ 0 คือ noa t นับเป็นตัวเลข
ตัวเลข n ต้องอยู่ในช่วง 1 ถึง 100 และค่าต้องอยู่ในช่วง 1 ถึง 500
อินพุตและเอาต์พุต
Input: This algorithm takes number of digits, and the sum value. Let the digit count is 3. and sum is 15. Output: Display the number of different 3-digit numbers whose sum is 15. The result is 69. (There are 69 different 3-digit numbers whose sum is 15)
อัลกอริทึม
นับ (หลัก ผลรวม)
อินพุต: ตัวเลขตามค่าที่กำหนด
ผลลัพธ์: นับจำนวน.
Begin if digit = 0, then return true when sum = 0 if memTable[digit, sum] is not vacant, then return memTable[digit, sum] answer := 0 for i := 0 to 9 do if sum – i >= 0, then answer := answer + count(digit – 1, sum - i) done return memTable[digit, sum] := answer End
numberCount(หลัก ผลรวม)
อินพุต: ตัวเลข ค่าที่กำหนด
ผลลัพธ์: ตัวเลขประเภทนั้นๆมีกี่ตัว
Begin define memTable and make all space vacant res := 0 for i := 1 to 9, do if sum – i >= 0, then res := res + count(digit – 1, sum - i) done return result End
ตัวอย่าง
#include<iostream>
#define ROW 101
#define COL 501
using namespace std;
unsigned long long int memTable[ROW][COL];
unsigned long long int count(int digit, int sum) {
if (digit == 0) //for 0 digit number check if the sum is 0 or not
return sum == 0;
if (memTable[digit][sum] != -1) //when subproblem has found the result, return it
return memTable[digit][sum];
unsigned long long int ans = 0; //set the answer to 0 for first time
for (int i=0; i<10; i++) //count for each digit and find numbers starting with it
if (sum-i >= 0)
ans += count(digit-1, sum-i);
return memTable[digit][sum] = ans;
}
unsigned long long int numberCount(int digit, int sum) {
for(int i = 0; i<ROW; i++) //initially all entries of memorization table is -1
for(int j = 0; j<ROW; j++)
memTable[i][j] = -1;
unsigned long long int result = 0;
for (int i = 1; i <= 9; i++) //count for each digit and find numbers starting with it
if (sum-i >= 0)
result += count(digit-1, sum-i);
return result;
}
int main() {
int digit, sum;
cout << "Enter digit count: "; cin >> digit;
cout << "Enter Sum: "; cin >> sum;
cout << "Number of values: " << numberCount(digit, sum);
} ผลลัพธ์
Enter digit count: 3 Enter Sum: 15 Number of values: 69