Summation of primes: Difference between revisions

no edit summary
(→‎{{header|Sidef}}: added a sublinear version)
No edit summary
 
(13 intermediate revisions by 12 users not shown)
Line 9:
=={{header|ALGOL 68}}==
{{libheader|ALGOL 68-primes}}
<langsyntaxhighlight lang="algol68">BEGIN # sum primes up to 2 000 000 #
PR read "primes.incl.a68" PR
# return s space-separated into groups of 3 digits #
Line 28:
LONG INT sum := 2;
FOR i FROM 3 BY 2 TO UPB prime DO
IF prime[ i ] THEN
sum +:= i
FI
OD;
print( ( space separate( whole( sum, 0 ) ), newline ) )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 43:
This isn't something that's likely to needed more than once — if at all — so you'd probably just throw together code like the following. The result's interesting in that although it's way outside AppleScript's integer range, its class is returned as integer in macOS 10.14 (Mojave)!
 
<langsyntaxhighlight lang="applescript">on isPrime(n)
if ((n < 4) or (n is 5)) then return (n > 1)
if ((n mod 2 = 0) or (n mod 3 = 0) or (n mod 5 = 0)) then return false
Line 67:
end sumPrimes
 
sumPrimes below 2000000</langsyntaxhighlight>
 
{{output}}
<syntaxhighlight lang ="applescript">142913828922</langsyntaxhighlight>
 
The result can be obtained in 4 seconds rather than 14 if the summing's instead combined with an Eratosthenean sieve:
 
<langsyntaxhighlight lang="applescript">on sumPrimes below this
set limit to this - 1
-- Is the limit 2 or lower?
Line 124:
end sumPrimes
 
sumPrimes below 2000000</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">print sum select 2..2000000 => prime?</syntaxhighlight>
 
{{out}}
 
<pre>142913828922</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SUMMATION_OF_PRIMES.AWK
BEGIN {
Line 161 ⟶ 169:
return(1)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 170 ⟶ 178:
=={{header|BASIC}}==
==={{header|FreeBASIC}}===
<langsyntaxhighlight lang="freebasic">#include "isprime.bas"
 
dim as integer sum = 2, i, n=1
Line 180 ⟶ 188:
next i
 
print sum</langsyntaxhighlight>
{{out}}<pre>142913828922</pre>
 
==={{header|GW-BASIC}}===
<langsyntaxhighlight lang="gwbasic">10 S# = 2
20 FOR P = 3 TO 1999999! STEP 2
30 GOSUB 80
Line 199 ⟶ 207:
140 Q = 1
150 RETURN
</syntaxhighlight>
</lang>
{{out}}<pre>142913828922</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include<stdio.h>
#include<stdlib.h>
 
Line 224 ⟶ 232:
printf( "%ld\n", s );
return 0;
}</langsyntaxhighlight>
{{out}}<pre>142913828922</pre>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">isqrt = proc (s: int) returns (int)
x0: int := s/2
if x0=0 then
Line 263 ⟶ 271:
start_up = proc ()
stream$putl(stream$primary_output(), int$unparse(sum_primes_to(2000000)))
end start_up </langsyntaxhighlight>
{{out}}
<pre>142913828922</pre>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby">def prime?(n) # P3 Prime Generator primality test
return false unless (n | 1 == 3 if n < 5) || (n % 6) | 4 == 5
sqrt = Math.isqrt(n)
Line 285 ⟶ 293:
puts "The sum of all primes below 2 million is #{(0i64..2000000i64).sum { |n| prime?(n) ? n : 0u64 }}"
 
</syntaxhighlight>
</lang>
{{out}}
<pre>The sum of all primes below 2 million is 142913828923.
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
procedure SummationOfPrimes(Memo: TMemo);
var I: integer;
var Sum: int64;
var Sieve: TPrimeSieve;
begin
Sieve:=TPrimeSieve.Create;
try
Sieve.Intialize(2000000);
Sum:=0;
for I:=0 to Sieve.PrimeCount-1 do
Sum:=Sum+Sieve.Primes[I];
Memo.Lines.Add(Format('Sum of Primes Below 2 million: %.0n',[Sum+0.0]));
finally Sieve.Free; end;
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
Sum of Primes Below 2 million: 142,913,828,922
 
Elapsed Time: 17.405 ms.
</pre>
 
 
=={{header|F_Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)]
<langsyntaxhighlight lang="fsharp">
// Summation of primes. Nigel Galloway: November 9th., 2021
printfn $"%d{primes64()|>Seq.takeWhile((>)2000000L)|>Seq.sum}"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 302 ⟶ 342:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: math.primes prettyprint sequences ;
 
2,000,000 primes-upto sum .</langsyntaxhighlight>
{{out}}
<pre>
Line 311 ⟶ 351:
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">s:=2;
for p=3 to 1999999 by 2 do if Isprime(p) then s:=s+p fi od;
!!s;</langsyntaxhighlight>
{{out}}<pre>142913828922</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn IsPrime( n as NSUInteger ) as BOOL
BOOL isPrime = YES
NSUInteger i
if n < 2 then exit fn = NO
if n = 2 then exit fn = YES
if n mod 2 == 0 then exit fn = NO
for i = 3 to int(n^.5) step 2
if n mod i == 0 then exit fn = NO
next
end fn = isPrime
 
 
local fn SumOfPrimes as long
long sum = 2, i, n = 1
for i = 3 to 2000000 step 2
if ( fn IsPrime(i) )
sum += i
n++
end if
next
end fn = sum
 
print fn SumOfPrimes
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
142913828922
</pre>
 
 
=={{header|Go}}==
{{libheader|Go-rcu}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 331 ⟶ 407:
}
fmt.Printf("The sum of all primes below 2 million is %s.\n", rcu.Commatize(sum))
}</langsyntaxhighlight>
 
{{out}}
Line 340 ⟶ 416:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Numbers.Primes (primes)
 
sumOfPrimesBelow :: Integral a => a -> a
Line 347 ⟶ 423:
 
main :: IO ()
main = print $ sumOfPrimesBelow 2000000</langsyntaxhighlight>
{{Out}}
<pre>142913828922</pre>
 
 
=={{header|J}}==
<syntaxhighlight lang=J>+/p: i. p:inv 2e6
142913828922</syntaxhighlight>
 
Here, p: represents what might be thought of as an array of primes, and its argument represents array indices of those primes. Similarly, the result p:inv represents the smallest index whose prime is no less than its argument.
 
So...
<syntaxhighlight lang=J> p:inv 2e6
148933
p: p:inv 2e6
2000003</syntaxhighlight>
 
Also, <code>i. n</code> returns a list of indices starting at zero and ending at one less than n (assuming n is a positive integer which of course it is, here).
 
And, (for people not familiar with J): <code>+/</code> sums a list (evaluates the hypothetical expression which would result from insert <code>+</code> between each element of that list).
 
=={{header|jq}}==
Line 357 ⟶ 449:
 
See [[Erd%C5%91s-primes#jq]] for a suitable definition of `is_prime/1` as used here.
<langsyntaxhighlight lang="jq">def sum(s): reduce s as $x (0; .+$x);
 
sum(2, range(3 ; 2E6; 2) | select(is_prime))</langsyntaxhighlight>
{{out}}
<pre>
Line 366 ⟶ 458:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Primes
 
@show sum(primes(2_000_000)) # sum(primes(2000000)) = 142913828922
</syntaxhighlight>
</lang>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Total[Most@NestWhileList[NextPrime, 2, # < 2000000 &]]</langsyntaxhighlight>
 
{{out}}<pre>
142913828922
</pre>
 
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
block(primes(2,2000000),apply("+",%%));
</syntaxhighlight>
Output
<syntaxhighlight lang="maxima">
/* 142913828922 */
</syntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="Nim">func isPrime(n: Natural): bool =
## Return true if "n" is prime.
## "n" is expected not to be a multiple of 2 or 3.
var k = 5
while k * k <= n:
if n mod k == 0 or n mod (k + 2) == 0: return false
inc k, 6
result = true
 
var sum = 2 + 3
var n = 5
while n < 2_000_000:
if n.isPrime:
inc sum, n
inc n, 2
if n.isPrime:
inc sum, n
inc n, 4
 
echo sum
</syntaxhighlight>
 
{{out}}
<pre>142913828922</pre>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">
s=2; p=3
while(p<2000000,if(isprime(p),s=s+p);p=p+2)
print(s)
</syntaxhighlight>
</lang>
{{out}}<pre>
142913828922
</pre>
=={{header|Pascal}}==
uses {{libheader|primTrialprimsieve}} [[Extensible_prime_generator#Pascal|Extensible_prime_generator]]
<langsyntaxhighlight lang="pascal">
program SumPrimes;
{$IFDEF FPC}{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$ENDIF}
{$ELSEIFDEF Windows} {$APPTYPE CONSOLE}{$ENDIF}
{$ENDIF}
uses
SysUtils,primTrialprimsieve;
var
p,sum : NativeInt;
begin
sum := actPrime0;
p := 0;
repeat inc(sum,p); p := NextPrime until p >= 2*1000*1000;
repeat inc(sum,p);p := Nextprime until p >= 2*1000*1000;
writeln(sum);
{$IFDEF WINDOWS} readln;{$ENDIF}
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 408 ⟶ 536:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Summation_of_primes
Line 415 ⟶ 543:
use List::Util qw( sum );
 
print sum( @{ primes( 2e6 ) } ), "\n";</langsyntaxhighlight>
{{out}}
<pre>
Line 422 ⟶ 550:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The sum of primes below 2 million is %,d\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_primes_le</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2e6</span><span style="color: #0000FF;">)))</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 433 ⟶ 561:
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">#!/usr/bin/python
 
def isPrime(n):
Line 448 ⟶ 576:
suma += i
n+=1
print(suma)</langsyntaxhighlight>
{{out}}
<pre>142913828922</pre>
 
===Functional===
<langsyntaxhighlight lang="python">'''Summatiom of primes'''
 
from functools import reduce
Line 497 ⟶ 625:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>142913828922</pre>
Line 504 ⟶ 632:
Or, more efficiently, assuming that we have a generator of primes:
 
<langsyntaxhighlight lang="python">'''Summatiom of primes'''
 
from itertools import count, takewhile
Line 568 ⟶ 696:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>142913828922</pre>
 
=={{header|Quackery}}==
 
<code>eratosthenes</code> and <code>isprime</code> are defined at[[Sieve of Eratosthenes#Quackery]].
 
<syntaxhighlight lang="Quackery"> 2000000 eratosthenes
0 2000000 times [ i isprime if [ i + ] ] echo
</syntaxhighlight>
 
{{out}}
 
<pre>142913828922</pre>
 
=={{header|Raku}}==
Slow, but only using compiler built-ins (about 5 seconds)
<syntaxhighlight lang="raku" perl6line>say sum (^2e6).grep: {.&is-prime};</langsyntaxhighlight>
{{out}}
<pre>142913828922</pre>
 
Much faster using external libraries (well under half a second)
<syntaxhighlight lang="raku" perl6line>use Math::Primesieve;
my $sieve = Math::Primesieve.new;
say sum $sieve.primes(2e6.Int);</langsyntaxhighlight>
Same output
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
see "working..." + nl
Line 600 ⟶ 741:
see "" + sum + nl
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 607 ⟶ 748:
142,913,828,922
done...
</pre>
 
=={{header|RPL}}==
{{works with|HP|49}}
≪ 0 1
'''WHILE''' NEXTPRIME DUP 2E6 <
'''REPEAT''' SWAP OVER + SWAP
'''END''' DROP
≫ '<span style="color:blue">TASK</span>' STO
{{out}}
<pre>
1: 142913828922
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang ="ruby">puts Prime.each(2_000_000).sum</langsyntaxhighlight>
{{out}}
<pre>142913828922
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="Rust">use primes::is_prime ;
 
fn main() {
println!("{}" , (2u64..2000000u64).filter( | &d | is_prime( d )).sum::<u64>() ) ;
}</syntaxhighlight>
{{out}}
<pre>
142913828922
</pre>
 
Line 618 ⟶ 782:
 
Built-in:
<langsyntaxhighlight lang="ruby">say sum_primes(2e6) #=> 142913828922</langsyntaxhighlight>
 
Linear algorithm:
<langsyntaxhighlight lang="ruby">func sum_primes(limit) {
var sum = 0
for (var p = 2; p < limit; p.next_prime!) {
Line 629 ⟶ 793:
}
 
say sum_primes(2e6)</langsyntaxhighlight>
 
Sublinear algorithm:
<langsyntaxhighlight lang="ruby">func sum_of_primes(n) {
 
return 0 if (n <= 1)
Line 655 ⟶ 819:
}
 
say sum_of_primes(2e6)</langsyntaxhighlight>
{{out}}
<pre>
Line 664 ⟶ 828:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./math" for Int, Nums
import "./fmt" for Fmt
 
Fmt.print("The sum of all primes below 2 million is $,d.", Nums.sum(Int.primeSieve(2e6-1)))</langsyntaxhighlight>
 
{{out}}
Line 676 ⟶ 840:
=={{header|XPL0}}==
Takes 3.7 seconds on Pi4.
<langsyntaxhighlight XPL0lang="xpl0">func IsPrime(N); \Return 'true' if N is a prime number >= 3
int N, I;
[if (N&1) = 0 then return false; \N is even
Line 693 ⟶ 857:
Format(1, 0); \don't show places after decimal point
RlOut(0, Sum);
]</langsyntaxhighlight>
 
{{out}}
Line 702 ⟶ 866:
=={{header|Yabasic}}==
{{trans|Python}}
<langsyntaxhighlight Yabasiclang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Summation_of_primes
// by Galileo, 04/2022
 
Line 718 ⟶ 882:
if isPrime(i) suma = suma + i
next
print str$(suma, "%12.f")</langsyntaxhighlight>
258

edits