# Find the Number With Even Sum of Digits using C++

C++Server Side ProgrammingProgramming

An integer number that can be completely divided by 2 is an even number. So in this article we are given the number n, and we need to find the nth number with an even sum of digits. The First five numbers with an even sum of digits are 2, 4, 6, 8, and 11. For example −

Input : n = 5
Output : 11
Explanation : First 5 numbers with even sum of digits are 2, 4, 6, 8, 11 i.e 5th
number is 11.

Input : 12
Output : 24

## Approach to find The Solution

Now you will get to know about two different procedures to find the solution to a given problem.

## Naive Approach

A simple solution to find the nth number is first to traverse through numbers starting from one and check for each number if the sum of its digit is even; if yes, then increment the counter by one until the value of counter becomes equal to n and finally that nth number will be the answer.

## Efficient Approach

An efficient approach to finding the nth number is by first checking the starting numbers with an even sum and searching for a pattern to find the answer. The first 20 numbers with even sum are 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, 28, 31, 33, 35, 37, 39 and 40. Looking at these first 20 numbers, we found that if the last digit of n is between 0 to 4, then the nth number will be 2*n, And if the nth number is between 5 to 9, then the nth number will be ( 2*n + 1).

## Example

#include <bits/stdc++.h>
using namespace std;
int main () {
long long int n = 13;
long long int result;
// finding the last digit of n
int last_digit = n % 10;
// checking if last digit is between 0 and 4
if (last_digit >= 0 && last_digit <= 4)
result = 2 * n;
// checking if last digit is between 5 and 9
else
result = (2 * n) + 1;
cout << "nth Number with even sum of digits: " << result;
return 0;
}

## Output

nth Number with even sum of digits: 26

## Explanation of the above code

• Find the last digit and check whether it lies between 0 and 4; if yes, then store 2*n as an answer in the result variable.
• Otherwise, check whether the last digit lies between 5 and 9; if yes, then store 2*n + 1 as an answer in the result variable.
• Print the nth number with an even sum of digits stored in the result variable.

## Conclusion

In this article, we discussed finding an nth number with an even sum of digits, where we can solve this problem in two ways that we understand in this article. We also write a C++ code to make a program to solve the same problem. We can write this code in other languages like C, java, python, etc. Hope you find this article helpful.

Updated on 26-Nov-2021 06:32:41