Skip to content

Commit 438f065

Browse files
committed
exercism 57
1 parent 84194cf commit 438f065

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,7 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
274274
54. [Nucleotide Count](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/nucleotide_count.rb)
275275
55. [Pythogorean Triplet](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/pythogorean_triplet.rb)
276276
56. [Collatz Conjecture](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/collatz_conjecture.rb)
277+
57. [Seive](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/seive.rb)
277278

278279
<a name="leetcode"/>
279280

Diff for: exercism/seive.rb

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#Problem: https://exercism.org/tracks/ruby/exercises/sieve
2+
3+
#Solution
4+
class Sieve
5+
def initialize(num)
6+
if num>1
7+
@input=(2..num).to_a
8+
else
9+
@input=[]
10+
end
11+
end
12+
13+
def primes
14+
return [] if @input==[]
15+
primes=[]
16+
@input.each do |num|
17+
next if num==nil
18+
primes.append(num)
19+
@input.map! {|x| x=x if x!=nil && x%num!=0 }
20+
end
21+
primes
22+
end
23+
end
24+
25+
#Solution 2
26+
class Sieve
27+
def initialize(top)
28+
@top = top
29+
end
30+
def primes
31+
numbers = [nil, nil, *2..@top]
32+
(2..Math.sqrt(@top)).each do |i|
33+
(i**2..@top).step(i) { |m| numbers[m] = nil } if numbers[i]
34+
end
35+
numbers.compact
36+
end
37+
end

0 commit comments

Comments
 (0)