Calculating Sum of Numbers with Digit Sums in a Specified Range
Problem Analysis
This problem requires calculating the sum of all integers from 1 to N where the sum of the digits of each integer falls within the inclusive range [A, B].
For example, with N=20, A=2, and B=5, the qualiyfing numbers are 2, 3, 4, 5, 11, 12, 13, 14, 15, and 20. Their total sum is 84.
Solution Approach
-
Input Processing:
- Read three integers: N (upper limit), A (minimum digit sum), and B (maximum digit sum).
-
Iterate Through Numbers:
- Loop through each integer X from 1 to N.
-
Calculate Digit Sum:
- For each integer X, compute the sum of its digits.
- This can be done by repeatedly extracting the last digit using modulo 10 and removing it using integer division by 10.
-
Condition Check:
- If the digit sum is between A and B (inclusive), add X to the cumulative total.
-
Output Result:
- Print the final sum of all qualifying numbers.
Code Implementation
#include <iostream>
using namespace std;
typedef long long int_type; // Define a type alias for large integers
int main() {
int_type upper_limit, min_sum, max_sum; // Variables for N, A, B
int_type total_sum = 0; // Initialize sum accumulator
cin >> upper_limit >> min_sum >> max_sum; // Read input values
// Process each number from 1 to N
for (int_type current_num = 1; current_num <= upper_limit; current_num++) {
int_type digit_total = 0; // Reset digit sum for current number
int_type number_copy = current_num; // Work with a copy to preserve original
// Calculate sum of digits
while (number_copy > 0) {
digit_total += number_copy % 10; // Add last digit
number_copy /= 10; // Remove last digit
}
// Check if digit sum is within specified range
if (digit_total >= min_sum && digit_total <= max_sum) {
total_sum += current_num; // Add qualifying number to total
}
}
cout << total_sum << endl; // Output final result
return 0;
}
Code Explanation
- Input Handling: The program reads three integers representing the problem parameters.
- Number Iteration: A loop processes each integer from 1 to N.
- Digit Sum Calculation: For each number, a while loop extracts and sums digits by repeatedly using modulo and division operations.
- Range Validation: An if statement checks whether the calculated digit sum falls within the specified inclusive bounds.
- Accumulation: Qualifying numbers are added to a running total.
- Output: The final accumulated sum is printed to standard output.