Valid Perfect Square

Problem

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Example 1:

Input: 16
Returns: True

Example 2:

Input: 14
Returns: False

Solution

Iterative Solution: O(sqrt(n)) time

public class Solution {
    public boolean isPerfectSquare(int num) {
        for (int i = 1; num > 0; i += 2) {
            num -= i;
        }
        return num == 0;
    }
}

Newton's method: O(1) time Formula: F(x) = 0 => x_n+1 = x_n - F(x_n)/F'(x_n)

public class Solution {
    public boolean isPerfectSquare(int num) {
        long x = num;
        while (x * x > num) {
            x = (x + num / x) / 2;
        }
        return x * x == num;
    }
}

Analysis

To check if a num is square number
We can have two approaches
First solution uses the property of square number which is num = 1 + 3 + 5 + ...
The second solution uses Newton's method which is initially to find the square root
After we find the expected square root x , we check if x * x == num to see if nums is a square number

results matching ""

    No results matching ""