Meeses
Meeses

Reputation: 144

Ruby for method seems to skip while going over array

Working on largest prime number euler problem. The for method at the bottom is supposed to go through the array of factors and test if they are prime numbers.

It works for smaller numbers, but for the test number (600851475143), there is one factor (104441) that is not a prime number, but the for method seems to skip over it. Other non-prime numbers are removed and the real prime numbers are kept. But this one number is begin skipped for some reason.

I know ruby has a Prime method and I am sure there are more eloquent ways to solve this problem. But this has been really bothering me. I appreciate your help. Thank you.

def make_array(num)
    array = []
    factors_array = []
    prime_array = []
    test_array = []
    x = 1
    while x <= Math.sqrt(num) #makes array of odd numbers below square root of number
        array << x
        x += 2
    end

    array.each do |x| #gets factors of number from array
        next if num % x != 0 
            factors_array << x
    end

    prime_array = factors_array
    puts "#{prime_array} before"
    factors_array.each do |i| #gets prime factors from factors
        for p in 2...i  #checks if numbers are prime numbers
            if i % p ==  0
                test_array << i
                not_prime = i
                prime_array.delete(not_prime)
            end
        end         
    end
    puts "#{test_array} test array"
    puts "largest prime factor is = #{prime_array.max}"
end
make_array(600851475143)
# answer is 104441, but it should be 6857

Upvotes: 0

Views: 76

Answers (1)

Phil Ross
Phil Ross

Reputation: 26100

The problem is caused by this line:

prime_array = factors_array

After this line, both the prime_array and factors_array variables reference (point to) the same Array object. When the prime_array.delete(not_prime) line executes, the factors_array.each iteration will skip a factor (because the next factors get shuffled up).

You can solve the problem by duplicating the array with the dup method:

prime_array = factors_array.dup

This will give you prime_array and factors_array variables referencing two independent Array objects that initially contain the same items. Modifications to the prime_array Array will not affect the iteration over the factors_array Array.

Upvotes: 2

Related Questions