You are given an integer n, find the smallest positive integer root of equation x, or else print -1 if no roots are found.
Equation: x^2 + s(x)*x – n = 0
where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system.
1 <= N <= 10^18
Input: N = 110 Output: 10 Explanation: x = 10 is the minimum root. As s(10) = 1 + 0 = 1 and 102 + 1*10 - 110=0. Input: N = 4 Output: -1 Explanation: there are no roots of the equation possible
A naive approach will be to iterate through all the possible values of X and find out if any such root exists but this won’t be possible as the value of n is very large.
An efficient approach will be as follows
Firstly let’s find the interval of possible values of s(x). Hence x^2 <= N and N <= 10^18, x <= 109. In other words, for every considerable solution x the decimal length of x does not extend 10 digits. So Smax = s(9999999999) = 10*9 = 90.
Let's brute force the value of s(x) (0 <= s(x) <= 90). Now we have an ordinary square equation. The deal is to solve the equation and to check that the current brute forced value of s(x) is equal to sum of digits of the solution. If the solution exists and the equality holds, we should get the answer and store the minimum of the roots possible.
Below is the implementation of the above approach
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Check whether one root of the Quadratic Equation is twice of other or not
- Print a number containing K digits with digital root D
- Nth root of a number using log
- N-th root of a number
- Square root of an integer
- Square root of a number using log
- Numbers in a Range with given Digital Root
- Program to calculate Root Mean Square
- Babylonian method for square root
- Find cubic root of a number
- Fast inverse square root
- Find Nth positive number whose digital root is X
- Find Cube root of a number using Log function
- Primitive root of a prime number n modulo n
- Square root of a number without using sqrt() function
- C program to find square root of a given number
- Digital Root of a given large integer using Recursion
- Calculating n-th real root using binary search
- Count of nodes which are at a distance X from root and leaves
- Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.