Java solution (Roots of square)


  • 0
    A

    Sum of first k natural number is given by:

    k(k+1)/2

    to find k we need to solve the equation, where sum = n
    we need to find positive root of the equation:
    k-sq + k - 2n = 0

    which is given by = (-b + sqrt(b-sq - 4ac))/2a

    public class Solution {
        public int arrangeCoins(int n) {
            if (n == 0) {
                return 0;
            }
            int b = 1;
            int a = 1;
            long c = -n*2l;
            int res = (int) (-b + Math.sqrt(b*b - 4*a*c))/2*a;
            
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.