
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Sum of the digits of a number N written in all bases from 2 to N/2 in C++
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 −
#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
- Related Articles
- Compute sum of digits in all numbers from 1 to n
- Number of digits in 2 raised to power n in C++
- Find largest sum of digits in all divisors of n in C++
- Sum of the series 1.2.3 + 2.3.+ … + n(n+1)(n+2) in C
- Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^n in C++
- Construct a frequency array of digits of the values obtained from x^1, x^2, ....., x^n\n in C++
- Find sum of Series with n-th term as n^2 - (n-1)^2 in C++
- Program to find last two digits of 2^n in C++
- Print all n-digit numbers whose sum of digits equals to given sum in C++
- Count pairs (a, b) whose sum of squares is N (a^2 + b^2 = N) in C++
- Sum of the series 1^1 + 2^2 + 3^3 + ... + n^n using recursion in C++
- Minimize the sum of squares of sum of N/2 paired formed by N numbers in C++
- n-th number whose sum of digits is ten in C++
- Count total number of digits from 1 to N in C++
- C++ program to find the sum of the series (1/a + 2/a^2 + 3/a^3 + … + n/a^n)

Advertisements