K
K
Kirill Popolov2014-04-25 17:08:29
ruby
Kirill Popolov, 2014-04-25 17:08:29

How to determine a perfect square in ruby?

A perfect square is an integer whose square root is an integer.
This is how I check if a number is a Fibonacci number:

def perf_square x
   return x == Math.sqrt(x) ** 2
end
perf_square(5 * (num ** 2) + 4) || perf_square(5 * (num ** 2) - 4) ? "IsFibo" : "IsNotFibo"

When the number num is small, there are no problems, but with large numbers, the square does not pass the test for "ideality".
Is it possible to solve the problem of finding a perfect square in ruby? If so, in which direction to dig?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
jj_killer, 2014-04-25
@ezhikov

def perf_square x
  Math.sqrt(x).to_r.denominator == 1
end

S
Sergey, 2014-04-25
Protko @Fesor

def is_perf_quare x
    return Math.sqrt(x).is_a? Integer
end

Not?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question