Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3 in C++
We are given two numbers L and R that define a range [L,R]. The goal is to find all numbers between L and R that are even, and sum of whose digits is divisible by 3.
We will do this by calculating the sum of digits of all even numbers between L and R and increment count if that sum%3==0.
Let us understand with examples.
Input − L=10, R=20
Output − Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3: 2
Explanation − Numbers between 10 and 20 that are even. 10,12,14,16,18,20. Sum of whose digits divisible by 3= 12 and 18.
Input − L=100, R=108
Output− Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3: 2
Explanation − Numbers between 100 and 108 that are even. 100,102,104,106,108. Sum of whose digits divisible by 3= 102 and 108.
Approach used in the below program is as follows
We take variables first and last to define range.
Function Digit_sum(int num) takes the number and returns the sum of its digits.
Using while loop, till num!=0, add num%10, (unit digit) to total.
Divide num by 10 to reduce it.
At the end total will have sum of all digits.
Function divisible_3(int first, int last) takes the range of numbers and returns the count of even numbers that have digit sum divisible by 3.
Starting from index i=first to i<=last. Check if number i is even. (i%2==0).
If true, then calculate sum of digits of i by calling Digit_sum(i). If that sum%3==0. Then increment count.
At the end of for loop return count as result.
Example
#include <bits/stdc++.h>
using namespace std;
int Digit_sum(int num){
int total = 0;
while (num!= 0){
total += num % 10;
num = num / 10;
}
return total;
}
int divisible_3(int first, int last){
int count = 0;
for (int i = first; i <= last; i++){
if (i % 2 == 0 && Digit_sum(i) % 3 == 0){
count++;
}
}
return count;
}
int main(){
int first = 300, last = 500;
cout<<"Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3 are: "<<divisible_3(first, last);
return 0;
}
Output
If we run the above code it will generate the following output −
Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3 are: 34