Saturday 25 July 2015

efficiently finding, number is multiple of 3 or not..(in ruby PL)
#author "shivamzaz"
#efficient for nu,ber is multipe of three or not.
#level "medium"
#specially use of bitwise operator
'''Example: 23 (00..10111)
    1) Get count of all set bits at odd positions (For 23 it’s 3).
    2) Get count of all set bits at even positions (For 23 it’s 1).
    3) If difference of above two counts is a multiple of 3 then number is also a multiple of 3.'''
#<---------------------Happy Coding-------------------------< implementation in #ruby>--------------------------Happy Coding---------------------->
g=gets().chomp.to_i
odd=0
even=0
for i in 1.upto(8)
    if(((g & (1<<(i-1)))>0) && (i%2!=0))    #(>0  becoz ruby have'nt if(1) type of stmts while takes if(1>0) means to say conditional stmts..
        odd+=1
        #puts("odd :#{i}")
    elsif(((g & (1<<(i-1)))>0) && (i%2==0))
        even+=1
        #puts("even :#{i}")

    else
        p+=1
    end
end
puts odd
puts even
if((odd-even)%3==0)
    puts("multiple of three ")
else
    puts("not multiples of three")
end

No comments:

Post a Comment