joedoe
joedoe

Reputation: 49

How to multiply integer digits between them?

I want to my n to multiply with next number for example if n=99 i want it to 9*9 and then return a result, and then i want the result (9*9 = 81 then 8*1 = 8) to multiply until it becomes 1 digit.

Here's my code:

def persistence(n) 
  if n <= 9
    puts n
  else
    n.to_s.each_char do |a|
      a.to_i * a.to_i unless n < 9
      puts a.to_i
    end
  end 
end

and i want it to return this:

persistence(39) # returns 3, because 3*9=27, 2*7=14, 1*4=4
             # and 4 has only one digit

persistence(999) # returns 4, because 9*9*9=729, 7*2*9=126,
              # 1*2*6=12, and finally 1*2=2

persistence(4) # returns 0, because 4 is already a one-digit number

Upvotes: 1

Views: 643

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

def persistence(n)
  0.step.each do |i|
    break i if n < 10
    n = n.digits.reduce(:*)
  end
end

persistence 4                  #=> 0
persistence 39                 #=> 3
persistence 999                #=> 4
persistence 123456789123456789 #=> 2

Regarding the last result, note that 2*5*2*5 #=> 100.

Upvotes: 0

kiddorails
kiddorails

Reputation: 13014

def persistence(n)
   i = 0
   while n.to_s.length != 1
     n = n.to_s.each_char.map(&:to_i).reduce(:*)
     i +=1
   end
   i
end

persistence(39) #=> 3
persistence(999) #=> 4

Other version:

def p(n, acc)
  return acc if n <= 9
  p(n.to_s.each_char.map(&:to_i).reduce(:*), acc+1)
end
def persistence(n)
  p(n, 0)
end

I will leave the breaking down of method and understanding what's happening and what is the difference b/w two variations to you. Will love to see your comment explaining it.

Upvotes: 1

Related Questions