Project Euler #50 - Consecutive prime sum - Ruby - ruby

I'm trying to solve Project Euler problem #50 (https://projecteuler.net/problem=50) where the problem is defined as:
Which prime, below one-million, can be written as the sum of the most
consecutive primes?
I've come up with two different solutions both giving the same wrong answer which leads me to believe the error happens as I'm building my list of primes, however, I can't seem to find any error. My solutions also seem to work for N = 10 and N = 100 but not N = 1000. Any help is appreciated.
Solution 1: (output = 958577)
require 'Prime'
# Initialising primes
N = 1_000_000
primes = {}
(2..N).each do |i|
primes[i] = true
end
i = 2
while i * i <= N
if primes[i]
j = i
while i * j <= N
primes[i * j] = false
j += 1
end
end
i += 1
end
# New prime list where total sum is less than N
new_primes = []
i = 2
sum = 0
while sum + i < N
if primes[i]
new_primes << i
sum += i
end
i += 1
end
# Keep removing last prime from list until total sum is prime
while true
if Prime.prime?( new_primes.inject(0, :+) )
puts new_primes.inject(0, :+)
break
else
new_primes.delete_at(-1)
end
end
Solution 2: (output = 958577)
require 'Prime'
# Initialising primes
N = 1_000_000
primes = {}
(2..N).each do |i|
primes[i] = true
end
i = 2
while i * i <= N
if primes[i]
j = i
while i * j <= N
primes[i * j] = false
j += 1
end
end
i += 1
end
sum = 0
max = 0
i = 2
while i < N
if primes[i]
sum += i
if sum < N && Prime.prime?(sum)
max = sum
end
end
i += 1
end
puts max

(w.r.t to Solution 2) Your method to find primes seems correct. The problem is with your logic. If the primes less than N are p_1,p_2,..,p_k, then you are only considering
only the sums p_1, p_1+p_2, p_1+p_2+p_3,...,p_1+p_2+..+p_k. What about sums not starting from p_1, say p_3+p_4.

Related

How to loop over an entire method until you achieve what you want ? (ruby)

I'm learning ruby and practicing with codewars, and I've come to a challenge that I feel I mainly understand (rudimentarily) but I'm unable to figure out how to continue looping over the method until I reach the result I'm looking for.
The challenge is asking to reduce a number, by multiplying its digits, until the multiplication results in a single digit. In the end it wants you to return the number of times you had to multiply the number until you arrived at a single digit. Example -> given -> 39; 3 * 9 = 27, 2 * 7 = 14, 1 * 4 = 4; answer -> 3
Here's my code :
def persistence(n)
if n < 10
return 0
end
arr = n.to_s.split("")
sum = 1
count = 0
arr.each do |num|
sum *= num.to_i
if num == arr[-1]
count += 1
end
end
if sum < 10
return count
else
persistence(sum)
end
end
Thanks for your help!
Your function is looking great with recursion but you are reseting the count variable to 0 each time the loop runs, I think if you use an auxiliar method it should run ok:
this is in base of your code with minor improvements:
def persistence(n)
return 0 if n < 10
count = 0
multiply_values(n, count)
end
def multiply_values(n, count)
arr = n.to_s.chars
sum = 1
arr.each do |num|
sum *= num.to_i
if num == arr[-1]
count += 1
end
end
if sum < 10
return count
else
multiply_values(sum, count)
end
end
a shorter solution could be to do:
def persistence(n)
return 0 if n < 10
multiply_values(n, 1)
end
def multiply_values(n, count)
sum = n.to_s.chars.map(&:to_i).reduce(&:*)
return count if sum < 10
multiply_values(sum, count + 1)
end
and without recursion:
def persistence(n)
return 0 if n < 10
count = 0
while n > 10
n = n.to_s.chars.map(&:to_i).reduce(&:*)
count += 1
end
count
end
Let's look at a nicer way to do this once:
num = 1234
product = num.to_s.split("").map(&:to_i).reduce(&:*)
Breaking it down:
num.to_s.split("")
As you know, this gets us ["1", "2", "3", "4"]. We can easily get back to [1, 2, 3, 4] by mapping the #to_i method to each string in that array.
num.to_s.split("").map(&:to_i)
We then need to multiply them together. #reduce is a handy method. We can pass it a block:
num.to_s.split("").map(&:to_i).reduce { |a, b| a * b }
Or take a shortcut:
num.to_s.split("").map(&:to_i).reduce(&:*)
As for looping, you could employ recursion, and create product_of_digits as a new method for Integer.
class Integer
def product_of_digits
if self < 10
self
else
self.to_s.split("").map(&:to_i).reduce(&:*).product_of_digits
end
end
end
We can now simply call this method on any integer.
1344.product_of_digits # => 6

Nuances of where to define a variable in ruby code

I've just started learning ruby, and the position of where variables are defined somewhat elude me. For example, why does this code work:
def two_sum(nums)
result = nil
i = 0
while i < nums.length
k = (nums.length - 1)
if nums[i] + nums[k] == 0
result = [i,k]
end
i += 1
k -= 1
end
return result
end
And why does this code not work:
def two_sum(nums)
result = nil
i = 0
k = (nums.length - 1)
while i < nums.length
if nums[i] + nums[k] == 0
result = [i,k]
end
i += 1
k -= 1
end
return result
end
Thank you in advance!
I think you code might just have a bug
while i < nums.length
k = (nums.length - 1)
...
k -= 1 # this statement has no effect!
end
Above, the value if k is always (nums.length - 1) because you reassign it at the begin of each iteration. The other statement has no effect.
k = (nums.length - 1)
while i < nums.length
...
k -= 1
end
Above, the value of k starts at (nums.length - 1) in the first iteration and is then reduced by 1 for each iteration.
Pro tipp —
It is very unusual in Ruby to use a for/while/until loop. If you want to loop over all elements use each or each_with_index instead
array.each { |each| ... }
array.each_with_index { |each, n| ... }

Project Euler #3 Ruby

The task:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
The correct answer is 6857.
My code:
def prime?(n)
(2..(n-1)).each { |x| false if n % x == 0 }
true
end
x = 2
prime_factor_arr = []
number = 600_851_475_143
while x < number
if number % x == 0 && prime?(x)
prime_factor_arr << x
number = number / x
end
x += 1
end
puts prime_factor_arr.last
puts prime?(prime_factor_arr.last)
puts prime_factor_arr
In the above case, I get 1471 as the largest prime. If I change the code to:
while x < (number / x)
if number % x == 0 && prime?(x)
prime_factor_arr << x
end
x += 1
end
I get 486847. The array printed in the end is:
[71, 839, 1471, 6857, 59569, 104441, 486847]
It is not clear to me why my code does not work. Could anybody help?
For the answer to the question, Sergio is right. But the code Sergio suggests (as well as yours) will not work correctly when number is a prime itself.
A better way to write is:
def prime?(n); (2...n).none?{|x| n.%(x).zero?} end
number = 600_851_475_143
number.downto(1).find{|x| number.%(x).zero? and prime?(x)}
Try this.
def prime? n
(2..(n-1)).each { |x| return false if n % x == 0 }
true
end
n = 600_851_475_143
a = []
product_sum = 1
x = 2 # 2 is the first prime number
while product_sum < n
if n % x == 0 && prime?(x)
a << x
product_sum *= x
end
x += 1
end
puts "The answer is #{a.last}"
The prime lib (from standard lib) is very nice for Project Euler. But it takes the fun out of this one:
require "prime"
600851475143.prime_division.last.first # => 6857

Ruby - Why does this minor function change result in a big time difference?

This script is for Project Euler #14
I am refactoring it and all I did was grab 1 line of code n.even? ? n = n/2 : n = (3*n) + 1 and made it into it's own function. This change increase the execution time by 5 seconds.
Why would that happen?
Before:
def longest_collatz_sequence1(count)
check = []
while count >= 1
n = count
seq = [count]
while n > 1
n.even? ? n = n/2 : n = (3*n) + 1
seq << n
end
count -= 1
check << seq
value = sequence_check(check) if check.length == 2
end
puts "The number that produces the largest chain is: #{value[0][0]}"
end
def sequence_check(check)
check[0].length > check[1].length ? check.delete_at(1) : check.delete_at(0)
check
end
s = Time.new
longest_collatz_sequence1 1000000
puts "elapsed: #{Time.new-s}"
#~12.2 seconds
After:
def longest_collatz_sequence1(count)
check = []
while count >= 1
n = count
seq = [count]
while n > 1
n=collatz(n)
seq << n
end
count -= 1
check << seq
value = sequence_check(check) if check.length == 2
end
puts "The number that produces the largest chain is: #{value[0][0]}"
end
def collatz(n)
n.even? ? n = n/2 : n = (3*n) + 1
end
def sequence_check(check)
check[0].length > check[1].length ? check.delete_at(1) : check.delete_at(0)
check
end
s = Time.new
longest_collatz_sequence1 1000000
puts "elapsed: #{Time.new-s}"
#~17.7 seconds

Getting a 'nil:Nil Class' error in Ruby, but the array doesn't seem to empty

I'm trying to code the 'Sieve of Eratosthenes' in Ruby and I'm having difficulty in the second 'while' loop. I want to test to see if integers[j] % integers[0] == 0, but the compiler keeps giving me a nil:Nil Class error at this line. I can't figure out the problem.
n = gets.chomp.to_i
puts
while n < 2
puts 'Please enter an integer >= 2.'
puts
n = gets.chomp.to_i
puts
end
integers = []
i = 0
while i <= n - 3
integers[i] = i + 2
i += 1
end
primes = []
j = 1
while integers != []
primes.push integers[0]
while j <= integers.length
if integers[j] % integers[0] == 0
integers.delete(integers[j])
end
j += 1
end
integers.shift
j = 1
end
puts integers
puts
puts primes
Thanks in advance for any help!
It's an off-by-one error. You're testing for j <= integers.length. So, for example, if you array has five items, the last iteration will be integers[5]. But the last index in a five-item array is 4 (because it starts at 0). You want j < integers.length.

Resources