
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
Find Number of Solutions to 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
Advertisements