ruby how could i make this factorization recursive till i end with a binary number?

287 views Asked by At

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
1

There are 1 answers

0
Eric Duminil On

You want to learn, so I won't do all the work for you.

Step 1

Please write those 3 methods :

def get_factors(integer)
  # return an Array of Integers:
  # get_factors(28) -> [2,2,7]
end

def get_factor_index(prime)
  # return the index of prime in Prime.all :
  # 2 -> 0
  # 7 -> 2
end

def array_to_binary(nested_array)
  # convert nested_array (with 0s in leaves) to binary
  # [[0],[0],[[0]]] -> "1101101110111"
  # Hint : Use Array#to_s, and then String#gsub 3 times to convert ',' to '', and '[' or ']' to 1
end

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 :

require "prime"

def get_factors(integer)
  Prime.prime_division(integer)
end

def nested_array(factors)
  factors.flat_map { |factor, power| [factor] *   power }
end

def get_factor_index(nested_array)
  list=Prime.take(10000)
  temp=[]
  nested_array.each do |i|
    p = list.index(i)
    temp.push(p)
  end
  temp
end

def array_to_binary(array)
  temp=array.to_s
  temp=temp.gsub("[","1")
  temp=temp.gsub("]","1")
  temp=temp.gsub(",","")
  temp.gsub(" ","")
end

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.