Search code examples
rubyruby-1.8.7

ruby function that checks if one of given number is integer power of another one


Inspired from this post, I wanted to generalize the problem. to check if given number m is integer power of number n.

Here is my first attempt and and as I tested it, everything is ok.

Then I attempted to write something different inspired from a response to the post on the link. Main idea is to check if logarithm of one number on base of another is integer or not. For this reason I used natural logarithm knowing that,
logab/logac =logcb

(my ruby version is 1.8.7)

def m_is_power_of_n(m,n)

    #false by definiton

    f1  = (n==0 and m!=0)
    f2 = (n==1 and m!=1)

    #true by definition

    t1 = m==n
    t2 = m==1

    if f1 or f2
        return false
    elsif t1 or t2
        return true
    else
        a = Math.log(m)/Math.log(n) 
        return a.to_i == a #updated after steenslag's comment
        #if a.to_i == a
        #    return true
        #else 
        #    return false
        #end
    end
end

I don't know what I am doing wrong because when I pass arguments (36,6), (125,5) it returns true as I expected. But for (216,6) or (25,5) it returns false.

P.S. btw, I am a ruby newbie, all criticisms about coding style are welcome :)


Solution

  • You have a precision problem, as you could see if you used irb

    irb(main):001:0> Math.log(216)
    => 5.375278407684165
    irb(main):002:0> Math.log(6)
    => 1.791759469228055
    irb(main):003:0> Math.log(216)/Math.log(6)
    => 3.0000000000000004
    

    And unfortunately 3.0000000000000004 isn't equal to 3.

    You could possibly round the result...

    a = (Math.log(m)/Math.log(n)).round(14)