Summation of primes: Difference between revisions
(add fermat) |
(add c) |
||
Line 20: | Line 20: | ||
print sum</lang> |
print sum</lang> |
||
{{out}}<pre>142913828922</pre> |
|||
=={{header|C}}== |
|||
<lang c>#include<stdio.h> |
|||
#include<stdlib.h> |
|||
int isprime( int p ) { |
|||
int i; |
|||
if(p==2) return 1; |
|||
if(!(p%2)) return 0; |
|||
for(i=3; i*i<=p; i+=2) { |
|||
if(!(p%i)) return 0; |
|||
} |
|||
return 1; |
|||
} |
|||
int main( void ) { |
|||
int p; |
|||
long int s = 2; |
|||
for(p=3;p<2000000;p+=2) { |
|||
if(isprime(p)) s+=p; |
|||
} |
|||
printf( "%ld\n", s ); |
|||
return 0; |
|||
}</lang> |
|||
{{out}}<pre>142913828922</pre> |
{{out}}<pre>142913828922</pre> |
||
Line 27: | Line 52: | ||
!!s;</lang> |
!!s;</lang> |
||
{{out}}<pre>142913828922</pre> |
{{out}}<pre>142913828922</pre> |
||
=={{header|Go}}== |
=={{header|Go}}== |
Revision as of 09:46, 8 November 2021
- Task
The task description is taken from Project Euler (https://projecteuler.net/problem=10)
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17
Find the sum of all the primes below two million
BASIC
FreeBASIC
<lang freebasic>#include "isprime.bas"
dim as integer sum = 2, i, n=1 for i = 3 to 2000000 step 2
if isprime(i) then sum += i n+=1 end if
next i
print sum</lang>
- Output:
142913828922
C
<lang c>#include<stdio.h>
- include<stdlib.h>
int isprime( int p ) {
int i; if(p==2) return 1; if(!(p%2)) return 0; for(i=3; i*i<=p; i+=2) { if(!(p%i)) return 0; } return 1;
}
int main( void ) {
int p; long int s = 2; for(p=3;p<2000000;p+=2) { if(isprime(p)) s+=p; } printf( "%ld\n", s ); return 0;
}</lang>
- Output:
142913828922
Fermat
<lang fermat>s:=2; for p=3 to 1999999 by 2 do if Isprime(p) then s:=s+p fi od; !!s;</lang>
- Output:
142913828922
Go
<lang go>package main
import (
"fmt" "rcu"
)
func main() {
sum := 0 for _, p := range rcu.Primes(2e6 - 1) { sum += p } fmt.Printf("The sum of all primes below 2 million is %s.\n", rcu.Commatize(sum))
}</lang>
- Output:
The sum of all primes below 2 million is 142,913,828,922.
PARI/GP
<lang parigp> s=2; p=3 while(p<2000000,if(isprime(p),s=s+p);p=p+2) print(s) </lang>
- Output:
142913828922
Ring
<lang ring> load "stdlib.ring" see "working..." + nl sum = 2 limit = 2000000
for n = 3 to limit step 2
if isprime(n) sum += n ok
next
see "The sum of all the primes below two million:" + nl see "" + sum + nl see "done..." + nl </lang>
- Output:
working... The sum of all the primes below two million: 142,913,828,922 done...
Wren
<lang ecmascript>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)))</lang>
- Output:
The sum of all primes below 2 million is 142,913,828,922.