ruby prime1.rb

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby prime1.rb相关的知识,希望对你有一定的参考价值。

# As a user I would like to pass a value and get all the factors returned in a collection
# To find a factorial the base case is an empty collection if the value is equal to 1
# If the value passed is greater than base case, find all numbers divisible but itself or 1 in range (2..passed value)
# Add result to factor of passed valuse divided by result

require 'Benchmark'
def prime_factors(n)
	return [] if n <= 1
	factorial = (2..n).find { |x| n % x == 0}
	[factorial] + prime_factors(n/factorial)
end


p prime_factors(10)
p prime_factors(3) 
p prime_factors(6)
p prime_factors(8)
puts
p prime_factors(3) == [3]
p prime_factors(6) == [2,3]
p prime_factors(8) == [2,2,2]
p prime_factors(25) == [5,5]
p prime_factors(123123123) == [3, 3, 41, 333667]


# test 1 same input
puts Benchmark.measure {1000.times {prime_factors(10) } }
puts
puts Benchmark.measure {1000.times {prime_factors(8) } }
puts 
puts Benchmark.measure {1000.times {prime_factors(7) } }
puts
puts Benchmark.measure {1000.times {prime_factors(6) } }
puts 
puts Benchmark.measure {1000.times {prime_factors(5) } }
puts
puts Benchmark.measure {1000.times {prime_factors(4) } }
puts 
 def prime_factors(n)
  prime_array = []
  return prime_array if n <=1
  factor = (2..n).find {|x| n % x == 0}
  prime_array << factor
  prime_array + prime_factors(n / factor)
 end

p prime_factors(3)         #== [3]
p prime_factors(6)         #== [2,3]
p prime_factors(8)         #== [2,2,2]
p prime_factors(25)        #== [5,5]
p prime_factors(123123123) #== [3, 3, 41, 333667]
def prime_factor(num)
  array = []
  while num.even?
    num /= 2
    array.push(2)
  end
  (3..Math.sqrt(num).ceil).each do |factor|
    while num % factor == 0
      num /= factor
      array.push(factor)
    end
  end
  array.push(num)
end

p prime_factor(873)
p prime_factor(12056)
p prime_factor(123123123)
require 'prime'

def prime_factors(n) # 873
  last_factor = n
  lowest_prime_divisor = 2
  prime_array = []

  until last_factor.prime?

    if last_factor % lowest_prime_divisor == 0
      prime_array << lowest_prime_divisor
      last_factor /= lowest_prime_divisor
      lowest_prime_divisor = 2
    else
      until lowest_prime_divisor.prime?
        lowest_prime_divisor += 1
      end
    end

  end

  prime_array << last_factor
  prime_array

end

puts prime_factors(92)

以上是关于ruby prime1.rb的主要内容,如果未能解决你的问题,请参考以下文章

Ruby运算符

Ruby 25 岁了!Ruby 之父说 Ruby 3 有望 3 倍提速

如何学习ruby?Ruby学习技巧分享

ruby Ruby脚本,看看是否用openssl编译了ruby

什么是ruby?

ruby和ruby ee