Skip to content

Commit 6228f86

Browse files
committed
new file: Math/dirichlet_hyperbola_method.sf
1 parent 472490c commit 6228f86

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

Math/dirichlet_hyperbola_method.sf

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#!/usr/bin/ruby
2+
3+
# Simple implementation of Dirichlet's hyperbola method.
4+
5+
# This is one of the most beautiful formulas in mathmematics!
6+
7+
# See also:
8+
# https://en.wikipedia.org/wiki/Dirichlet_hyperbola_method
9+
10+
func dirichlet_hyperbola_method(n, g = { _ }, h = { _ }) {
11+
var s = n.isqrt
12+
13+
var A = sum(1..s, {|a|
14+
g(a) * sum(1..floor(n/a), {|b|
15+
h(b)
16+
})
17+
})
18+
19+
var B = sum(1..s, {|b|
20+
h(b) * sum(1..floor(n/b), {|a|
21+
g(a)
22+
})
23+
})
24+
25+
var C = sum(1..s, {|a|
26+
g(a) * sum(1..s, {|b|
27+
h(b)
28+
})
29+
})
30+
31+
A + B - C
32+
}
33+
34+
func test_sum(n, g, h) {
35+
sum(1..n, {|k|
36+
k.divisors.sum {|d|
37+
g(d) * h(k/d)
38+
}
39+
})
40+
}
41+
42+
func g(n) { n }
43+
func h(n) { moebius(n) }
44+
45+
say 20.of { test_sum(_, g, h) }
46+
say 20.of { dirichlet_hyperbola_method(_, g, h) }
47+
48+
__END__
49+
[0, 1, 2, 4, 6, 10, 12, 18, 22, 28, 32, 42, 46, 58, 64, 72, 80, 96, 102, 120]
50+
[0, 1, 2, 4, 6, 10, 12, 18, 22, 28, 32, 42, 46, 58, 64, 72, 80, 96, 102, 120]

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ A simple collection of Sidef scripts.
117117
* [Cuban primes](./Math/cuban_primes.sf)
118118
* [Difference of two squares solutions](./Math/difference_of_two_squares_solutions.sf)
119119
* [Digamma function](./Math/digamma_function.sf)
120+
* [Dirichlet hyperbola method](./Math/dirichlet_hyperbola_method.sf)
120121
* [Discrete fourier transform](./Math/discrete_fourier_transform.sf)
121122
* [Divisors of factorial in range iterator](./Math/divisors_of_factorial_in_range_iterator.sf)
122123
* [Draw grid of squares](./Math/draw_grid_of_squares.sf)

0 commit comments

Comments
 (0)