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
- Print a number containing K digits with digital root D
- N-th root of a number
- Square root of a number using log
- Square root of an integer
- Fast inverse square root
- Find cubic root of a number
- Program to calculate Root Mean Square
- Babylonian method for square root
- Numbers in a Range with given Digital Root
- Square root of a number without using sqrt() function
- Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
- Primitive root of a prime number n modulo n
- Count of nodes which are at a distance X from root and leaves
- Find Nth positive number whose digital root is X
- Calculating n-th real root using binary search
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.