Skip to content

Commit 43f49a1

Browse files
committed
Add Ruby Sieve of Sundaram snippet
1 parent 993a50a commit 43f49a1

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

snippets/ruby/math-and-numbers/calculate-compound-interest.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ contributors: axorax
66
tags: ruby,math,compound interest,finance
77
---
88

9-
```ruby
9+
```rb
1010
def compound_interest(principal, rate, time, n = 1)
1111
principal * (1 + rate / n) ** (n * time)
1212
end
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
title: Find all primes up to integer (Sieve of Sundaram)
3+
description: Finds all the prime numbers up to a specific integer.
4+
author: ACR1209
5+
tags: ruby,math,prime numbers
6+
---
7+
8+
```rb
9+
def sieve_of_sundaram(limit)
10+
n = (limit - 1) / 2
11+
marked = Array.new(n + 1, false)
12+
13+
(1..n).each do |i|
14+
j = i
15+
while (i + j + 2 * i * j) <= n
16+
marked[i + j + 2 * i * j] = true
17+
j += 1
18+
end
19+
end
20+
21+
primes = [2]
22+
(1..n).each do |i|
23+
primes << (2 * i + 1) unless marked[i]
24+
end
25+
26+
primes
27+
end
28+
29+
# Usage:
30+
print sieve_of_sundaram(30) # Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
31+
```

0 commit comments

Comments
 (0)