Find the number of solutions to the given equation in C++


In this problem, we are given three integer values A, B, C. Our task is to find the number of solutions to the given equation.

Equation

X = B*Sm(X)^A + C

where Sm(X) is the sum of digits of X.

We need to count all the values of X such that it satisfies the above equation where X can be any number between 1 to 109.

Let’s take an example to understand the problem,

Input

A = 3, B = 6, C = 4

Output

3

Solution Approach

A solution to solve the problem is by counting the number of values of X. For this, the sum of digits plays an important role. The maximum digit sum is 81 (for the max value 999999999). And for each value of sum, we can get a solution to the equation.

We will be counting the values that satisfy the equal form value 1 to 81.

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
int countSolutions(int a, int b, int c){
   int solutionCount = 0;
   for (int digSum = 1; digSum <= 81; digSum++) {
      int solVal = b * pow(digSum, a) + c;
      int temp = solVal;
      int sum = 0;
      while (temp) {
         sum += temp % 10;
         temp /= 10;
      }
      if (sum == digSum && solVal < 1e9)
         solutionCount++;
   }
   return solutionCount;
}
int main(){
   int a = 3, b = 6, c = 4;
   cout<<"The number of solutions of the equations is "<<countSolutions(a, b, c);
   return 0;
}

Output

The number of solutions of the equations is 3

Updated on: 11-Feb-2022

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements