I am trying to find the sum of all multiples of 3 or 5 below 10
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = 0
numbers.each do |number|
if number % 3 == 0 or number % 5 == 0
result += number
end
print result
end
I receive this: 0033814141423, but I expect 23, as it's the sum of 3, 5, 6, 9.
Your print statement is inside the loop. It should be moved outside.
numbers = [1,2,3,4,5,6,7,8,9]
result = 0
numbers.each do |number|
if number % 3 == 0 or number % 5 == 0
result += number
end
end
print result
A proper indentation will also help you to catch these errors. Moreover, you should use p to print out an information, not print.
With p each output would have been done on a new line. That would probably be an hint to understand the issue.
This is also a possible alternative using Enumerable#inject with an accumulator.
numbers = [1,2,3,4,5,6,7,8,9]
numbers.inject(0) do |acc, number|
acc + case
when number % 3 == 0 then number
when number % 5 == 0 then number
else 0
end
end
And a more compact form
numbers = [1,2,3,4,5,6,7,8,9]
numbers.lazy.select { |n| n % 3 == 0 || n % 5 == 0 }.inject(:+)
You may use Array#select method.
result = 0
[1,2,3,4,5,6,7,8,9].select{|i| i % 3 == 0 || i % 5 == 0}.each do |num|
result += num
end
or more shortly with inject.
[1,2,3,4,5,6,7,8,9].select{|i| i % 3 == 0 || i % 5 == 0}.inject(:+)
Well, what I did was something like this:
(1...10).to_a.select{|i| i%3==0 or i%5==0}.sum
Related
I am trying to get the first num factorials.
For example if num is 6 then we would want the first 6 factorials: 1,1,2,6,24,120
Below is my current solution. It always returns an extra factorial. So if num is 6 it returns 7 factorials.
def factorials_rec(num)
return [1] if num == 1
arr = factorials_rec(num-1)
arr << num * arr.last
end
Result [1, 1, 2, 6, 24, 120, 720]
Desired result [1, 1, 2, 6, 24, 120]
I only want 6 factorials but 7 are being returned.
Using recursion, how can I adjust this function to return the desired number of factorials.
I have tried
base case = return [1,1] if num == 2, etc..
arr << num * arr.last unless arr.length >= num, etc...
Try fixing the last line to:
arr << (num-1) * arr.last
I've seen solutions posted in other languages but not Ruby so I'm asking here.
Trying to find out the largest prime factor of 13195.
My code is as follows
# find out all numbers that divide without remainder into 13195
array = []
count = 2
13195.times do
if 13195 % count == 0
array.push(count)
end
count += 1
end
#From those numbers that divide cleanly into 13195, find out which are prime aka can only be divided by themselves and 1
new_count = 2
primes = 0
array.each do |x|
while new_count < x
if x % new_count != 0
else
if x > primes
primes = x
end
end
new_count += 1
end
end
puts primes
In my first loop I am populating an empty array with all the numbers that divide into 13195 without a remainder, from testing this piece of code seems to be working.
It's the second part of my solution that's the problem inside my each statement, can someone point me in the right direction?
I suggest you use Prime#prime_division:
require 'prime'
def largest_prime_factor(n)
Prime.prime_division(n).max_by(&:first).first
end
largest_prime_factor(13195)
#=> 29
(1..1000).to_a.sample(15).sort.each {|n| puts "%3d: %3d" % [n, largest_prime_factor(n)]}
61: 61
80: 5
88: 11
250: 5
304: 19
414: 23
514: 257
548: 137
679: 97
716: 179
754: 29
770: 11
906: 151
907: 907
968: 11
For example,
n = 13195
a = Prime.prime_division(n)
#=> [[5, 1], [7, 1], [13, 1], [29, 1]]
b = a.max_by(&:first)
#=> [29, 1]
b.first
#=> 29
It appears that the elements of the array returned by prime_division are in order of increasing prime factor. If that were guaranteed, one could just write:
Prime.prime_division(n).last.first
I used max_by in the event that the order of those elements is implementation-specific.
Shorter version:
require 'prime'
primes = Prime.each(13195).to_a
upper = primes.last
primes will have all primes from 0 to 13195 and upper obviously the last.
I set a limit of prime numbers to 100000 (to avoid of couple days of calculation of big numbers like 600851475143 =) )
def prime_factors(n)
prime_array = []
p = 2
if n < 2
return p
end
while p < n && p < 1000000
if n % p == 0
prime_array.push(p)
end
p +=1
end
primes = []
prime_array.size.times do |i|
if n > 1
n = n / prime_array[i]
primes.push(prime_array[i])
end
end
return primes.last
end
#prime_factors(600851475143)
puts prime_factors(600851475143)
#prime_factors(13195)
puts prime_factors(13195)
Another way to use prime_division:
require 'prime'
(13195).prime_division.map(&:first).max
=> 29
Your second loop can be re-written to do what is meant to do.
As I understand, your goal is to select from array, largest of such elements that are prime (divides by only 1 and itself). In other words, an element x is eligible if it is not divisible by any number between 2 and x-1.
result = array.select {|x| not (2..x-1).any? {|i| x % i == 0} }.max
#=> 29
Currently, your logic has some flaws. It is not resetting the value of new_count and hence you are getting wrong results. Here is corrected version:
array.each do |x|
is_prime = true
while new_count < x
if x % new_count == 0
is_prime = false
end
new_count += 1
end
new_count = 2
primes = x if is_prime and x > primes
end
Without using Prime#prime_division we can dived the problems into small parts. the first part if to write a method that determine whether a number if prime or not, which can be like :
def prime?(num)
if num < 2
return false
end
(2...num).each do |ele|
if num % ele == 0
return false
end
end
return true
end
then we can write our main method which is asking for the prime_factors of a number like:
def prime_factors(num)
prime_facts = []
(1..num).each do |i|
if num % i == 0 && prime?(i)
prime_facts << i
end
end
return prime_facts
end
print prime_factors(24) #=> [2, 3]
puts
print prime_factors(60) #=> [2, 3, 5]
puts
print prime_factors(13195) # [5, 7, 13, 29]
puts
I know similar questions have been asked before but they all seem so over complicated and I don't think i'm that far off, so was wondering if anyone knows how to tweak my code to get it to work. My goal is to save all prime numbers of a range into an array and then print that array. Below is my code so far
prime_array = []
(1...100).each do |num|
if Math.sqrt(num) % 2 == 0
prime_array.push(num)
end
end
prime_array
#=> [4, 16, 36, 64]
I've tried a few different options but have hit a wall and can't see what i need to do. I'm trying to keep it as simple as possible as I feel a lot of the answers out there a little over complicated. Thanks in advance.
Let's calculate the square root of 7 (a prime number) and 8 (a composite number):
Math.sqrt(7) #=> 2.6457513110645907
Math.sqrt(8) #=> 2.8284271247461903
This doesn't really help, does it? Apparently, you can't determine if a number is a prime number by calculating its square root.
Instead, you have to check the number's divisors. From Wikipedia:
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Let's determine the divisors of 7: (using the modulo operator %)
7 % 1 #=> 0 <- 7 is divisible by 1
7 % 2 #=> 1
7 % 3 #=> 1
7 % 4 #=> 3
7 % 5 #=> 2
7 % 6 #=> 1
7 % 7 #=> 0 <- 7 is divisible by 7
This satisfies the above definition - 7 is a prime number.
Now, let's determine the divisors of 8:
8 % 1 #=> 0 <- 8 is divisible by 1
8 % 2 #=> 0 <- 8 is divisible by 2
8 % 3 #=> 2
8 % 4 #=> 0 <- 8 is divisible by 4
8 % 5 #=> 3
8 % 6 #=> 2
8 % 7 #=> 1
8 % 8 #=> 0 <- 8 is divisible by 8
8 has two additional divisors 2 and 4. Therefore, 8 is not a prime number.
In Ruby, you could use select to find the divisors:
(1..7).select { |d| 7 % d == 0 } #=> [1, 7]
(1..8).select { |d| 8 % d == 0 } #=> [1, 2, 4, 8]
Finally, here's a variant of your Ruby code that checks if a given number num has exactly two divisors, 1 and num itself:
prime_array = []
(1...100).each do |num|
if (1..num).select { |d| num % d == 0 } == [1, num]
prime_array.push(num)
end
end
prime_array
#=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
The above code can be optimized. I leave that to you.
Method that returns prime numbers in an array in ruby
def is_prime?(number)
return false if number <2
(2..Integer.sqrt(number)).each do |divisor|
return false if number % divisor == 0
end
return number
end
def read_array(array)
primes = []
array.each do |num|
primes << num if is_prime?(num)
end
return primes
end
In irb to checkout the working of inject method I wrote down simple code to print the count of numbers divisible by 3 but somehow that's malfunctioning:
[1,2,3,4].inject(0) do |count,value|
if value % 3 == 0
count = count + 1
end
end
It is something minor but I am not getting a hold on it.
With inject, you need to return the memo-element on each iteration:
[1, 2, 3, 4].inject(0) do |count, value|
if value % 3 == 0
count = count + 1
end
count
end
#=> 1
Or, if you prefer the one-line version:
[1, 2, 3, 4].inject(0) { |c, v| c += 1 if v % 3 == 0; c }
#=> 1
Worth noting. In some cases, you can substitute inject for each_with_object, and avoid having to return the memo object, but since the return value of the latter is the original object passed in, it only works with objects passed by reference (i.e. not Fixnums.)
[1, 2, 3, 4].each_with_object(0) { |v, c| c += 1 if v % 3 == 0 }
#=> 0
So it turns out it was infact something minor. I didn't return the count at end of each loop so count was nil after first iteration since I didn't return it. Blunder!
[1,2,3,4].inject(0) do |count,value|
if value % 3 == 0
count = count + 1
end
count
end
Is there a more elegant way to achieve this below:
Input:
array = [1, 1, 1, 0, 0, 1, 1, 1, 1, 0]
Output:
4
My algo:
streak = 0
max_streak = 0
arr.each do |n|
if n == 1
streak += 1
else
max_streak = streak if streak > max_streak
streak = 0
end
end
puts max_streak
Similar to w0lf's answer, but skipping elements by returning nil from chunk:
array.chunk { |x| x == 1 || nil }.map { |_, x| x.size }.max
Edit: Another way to do this (that is less generic than Stefan's answer since you would have to flatten and split again if there was another number other than 0 and 1 in there, but easier to use in this case):
array.split(0).max.count
You can use:
array.chunk { |n| n }.select { |a| a.include?(1) }.map { |y, ys| ys.count}.max
ref: Count sequential occurrences of element in ruby array
You can use Enumerable#chunk:
p array.chunk{|x| x}.select{|x, xs| x == 1}.map{|x, xs| xs.size }.max
This is more concise, but if performance was important, I'd use your approach.
Edit: If you're in Ruby 2.2.2, you can also use the new Enumerable#slice_when method (assuming your input array consists of only 0s and 1s):
array.slice_when{|x,y| x < y }.map{|slice| slice.count 1 }.max
How about
array = [1, 1, 1, 0, 0, 1, 1, 1, 1, 0]
array.split(0).group_by(&:size).max.first #=> 4
The only bad thing - split(0)
Note: This only works with rails's ActiveSupport(extends Array with #split)
For ruby-only implementation
array.join.split("0").group_by(&:size).max.first #=> 4