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
- Count digits in a factorial | Set 2
- Write a program to reverse digits of a number
- Babylonian method for square root
- Given a number, find the next smallest palindrome
- Count numbers with same first and last digits
- Count digits in given number N which divide N
- Print all possible words from phone digits
- Find the smallest number whose digits multiply to a given number n
- Find next greater number with same set of digits
- Build Lowest Number by Removing n digits from a given number
- Compute sum of digits in all numbers from 1 to n
- Find number of solutions of a linear equation of n variables
- Total number of non-decreasing numbers with n digits
- Count of n digit numbers whose sum of digits equals to given sum
- Count total number of N digit numbers such that the difference between sum of even and odd digits is 1
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.