Algorithm Interview Questions: Square

 

Given an integral number, determine if it’s a square number:
In mathematics, a square number or perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself.

Output:

isSquare(-1) returns  false
isSquare(0) returns   true
isSquare(3) returns   false
isSquare(4) returns   true
isSquare(25) returns  true  
isSquare(26) returns  false

Python

import math
def is_square(n):
    upper_index = n
    lower_index = 0
    while upper_index >= 1:
      upper_index = math.ceil(upper_index/2)
      if upper_index**2 == n:
         return True
      elif upper_index**2 > n:
          continue
      elif upper_index**2 < n:
          for index in range(upper_index+1,(upper_index*2)+1):
             if index**2 == n:
                 return True
    return False # fix me

Go

package main

import (
	"fmt"
	"math"
)
func is_square(num int32) bool{
     n := float64(num)
     lower_bound := n
     for lower_bound >= 0 {
          lower_bound = math.Ceil(lower_bound/2)
          if math.Pow(lower_bound,2.0) == n{
             return true
          }else if math.Pow(lower_bound,2.0) > n{
             continue
          }else if math.Pow(lower_bound,2.0) < n{
              for i := lower_bound +1; i < lower_bound * 2; i += 1{
                     if  math.Pow(i,2.0) == n {
                            return true
                     }
              }
              return false
          }
     }
     return false
}
func main() {
	fmt.Println("Hello, playground")
	fmt.Println(is_square(10))
	fmt.Println(is_square(25))
	fmt.Println(is_square(0))
}

Rust

#![allow(unused)]
fn is_square(n: i32) -> bool{
    let mut lower_bound = n;
    while lower_bound >= 0{
      lower_bound = (lower_bound as f64 / 2.0 as f64).ceil() as i32;
      if lower_bound.pow(2) == n{
          return true
      }else if lower_bound.pow(2) > n{
          continue
      }else if lower_bound.pow(2) < n{
          for i in (lower_bound+1..lower_bound*2){
              if i.pow(2) == n{
                 return true
              }
          }
        return false
      }
    }
    return false

}
fn main() {
  assert_eq!(is_square(10),false);
  assert_eq!(is_square(25),true);
  assert_eq!(is_square(0),true);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s