i have this code, basically first i factorize for example the number 28 to: [2,2,7] and then i make a list of prime numbers and find the index of each factor in that list, so 2 is prime number with index 0 and 7 prime number with index 2 so it ends up like this: [[0],[0],[2]] with which another recursion would be: [[0],[0],[[0]]] which tranlated to binary would be: 1101101110111
but im stuck on this:
require 'prime'
def f(n)
Prime.prime_division(n).flat_map { |factor, power| [factor] * power }
end
n=rand(10000)
puts n
f=f (n)
require 'prime'
@list=Prime.take(10000)
g=[]
j=0
f.each do |j|
if j>10
i=f(@list.index(j))
g.push i
i=[]
else
g.push j
end
end
print g
You want to learn, so I won't do all the work for you.
Step 1
Please write those 3 methods :
and come back once you're done. We'll work on the recursion.
Step 2
I modified a bit your answer just a bit. To make it clearer, I tried to use different names for variables and methods. Also, the last line of a method is returned automatically by Ruby. You don't need to define an extra variable. Methods could probably be written more efficiently but I didn't want you to not recognize your code.
Your
get_factor_index
does more than what I asked for BTW. I'm not sure we can use it like this :Now, please write a method that uses all the above ones, converting 512 to "10000000001". I'm not sure it's the correct answer, but we'll work on that later.
Also, try this method on 20 (not 28!) and see what you get. Using the above methods, you could try to manually tailor a way to get
[[0],[0],[2]]
. It's not a problem if it just works for 20 at first.If you're feeling adventurous, try to get
[[0],[0],[[0]]]
with the above methods.