# Sum of the digits of a number N written in all bases from 2 to N/2 in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number N. Our task is to create a program to find the sum of the digits of the number N in bases from 2 to N/2.

So, we have to convert the base of the number to all bases from 2 to N/2 i.e. for n = 9, bases will be 2, 3, 4. And the find the sum of all digits in these bases.

Let’s take an example to understand the problem,

Input

N = 5

Output

2

Explanation

base from 2 to N/2 is 2.
52 = 101, sum of digits is 2.

To, solve this problem, we take every number from 2 to N/2 as a base. And then to calculate the sum of digits, we will repeatedly divide the N by base i.e. N = N/base, and add the remainder value to the sum. And then add the sum values found for each base to get the result.

## Example

Program to illustrate the working of our solution

Live Demo

#include <iostream>
using namespace std;
int findBaseSum(int n, int base, int &sum){
while (n > 0) {
sum += n % base;
n /= base;
}
return sum;
}
void CalcSumOfBaseDigits(int n, int &sum){
for (int base = 2; base <= n / 2; base++)
findBaseSum(n, base, sum);
}
int main(){
int N = 11;
int sum = 0;
CalcSumOfBaseDigits(N, sum);
cout<<"The sum of digits of "<<N<<" written in all bases from 2 to "<<(N/2)<<" is "<<sum;
return 0;
}

## Output

The sum of digits of 11 written in all bases from 2 to 5 is 14
Published on 06-Aug-2020 08:10:00