Project Euler #3 in Ruby solution times out -


i'm going through few of project euler problems practice problem solving using ruby. came following solution problem 3, , while works smaller numbers, never seems return value larger numbers. because of bignum? can describe me why it's timing out, , better way solve problem (preferably reasoning/info on what's going on behind scenes. i'm trying understand)

project euler problem:

the prime factors of 13195 5, 7, 13 , 29. largest prime factor of number 600851475143 ?

my solution:

def primecheck(number)   (2...number).each { |x| return false if number % x == 0}   true end  def largestprime(number1)   factors = []     (1..number1).each |i|       if number1 % == 0 && primecheck(i)         factors <<       end     end puts "the answer #{factors.last}" end  largestprime(600_851_475_143) 

hint: once you've found prime factor, can divide it. reduces range of remaining potential divisors have check.

using first example:

13195/5 = 2639, 2639/7  = 377, 377/13  = 29, 29/29   = 1, done. 

this way, had check 29 instead of way 13195.

there ways improve further, optimization alone should more enough simple problem.


Comments

Popular posts from this blog

Java sticky instances of class com.mysql.jdbc.Field aggregating -