Goldbach's comet: Difference between revisions
Content added Content deleted
(Nim solution.) |
|||
Line 799: | Line 799: | ||
[graphical object showing Goldbach's comet]</pre> |
[graphical object showing Goldbach's comet]</pre> |
||
=={{header|Nim}}== |
|||
{{libheader|nim-plotly}} |
|||
{{libheader|chroma}} |
|||
To display the Golbach’s comet, we use a library providing a Nim interface to “plotly”. The graph is displayed into a browser. |
|||
<syntaxhighlight lang="Nim">import std/[math, strformat, strutils, sugar] |
|||
import chroma, plotly |
|||
const |
|||
N1 = 100 # For part 1 of task. |
|||
N2 = 1_000_000 # For part 2 of task. |
|||
N3 = 2000 # For stretch part. |
|||
# Erathostenes sieve. |
|||
var isPrime: array[1..N1, bool] |
|||
for i in 2..N1: isPrime[i] = true |
|||
for n in 2..sqrt(N1.toFloat).int: |
|||
for k in countup(n * n, N1, n): |
|||
isPrime[k] = false |
|||
proc g(n: int): int = |
|||
## Goldbach function. |
|||
assert n > 2 and n mod 2 == 0, "“n” must be even and greater than 2." |
|||
for i in 1..(n div 2): |
|||
if isPrime[i] and isPrime[n - i]: |
|||
inc result |
|||
# Part 1. |
|||
echo &"First {N1} G numbers:" |
|||
var col = 1 |
|||
for n in 2..N1: |
|||
stdout.write align($g( 2 * n), 3) |
|||
stdout.write if col mod 10 == 0: '\n' else: ' ' |
|||
inc col |
|||
# Part 2. |
|||
echo &"\nG({N2}) = ", g(N2) |
|||
# Stretch part. |
|||
const Colors = collect(for name in ["red", "blue", "green"]: name.parseHtmlName()) |
|||
var x, y: seq[float] |
|||
var colors: seq[Color] |
|||
for n in 2..N3: |
|||
x.add n.toFloat |
|||
y.add g(2 * n).toFloat |
|||
colors.add Colors[n mod 3] |
|||
let trace = Trace[float](type: Scatter, mode: Markers, marker: Marker[float](color: colors), xs: x, ys: y) |
|||
let layout = Layout(title: "Goldbach’s comet", width: 1200, height: 400) |
|||
Plot[float64](layout: layout, traces: @[trace]).show(removeTempFile = true) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>First 100 G numbers: |
|||
1 1 1 2 1 2 2 2 2 3 |
|||
3 3 2 3 2 4 4 2 3 4 |
|||
3 4 5 4 3 5 3 4 6 3 |
|||
5 6 2 5 6 5 5 7 4 5 |
|||
8 5 4 9 4 5 7 3 6 8 |
|||
5 6 8 6 7 10 6 6 12 4 |
|||
5 10 3 7 9 6 5 8 7 8 |
|||
11 6 5 12 4 8 11 5 8 10 |
|||
5 6 13 9 6 11 7 7 14 6 |
|||
8 13 5 8 11 7 9 13 8 9 |
|||
G(1000000) = 5402 |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |