# Sum of primes between given range

Write the shortest code for finding the sum of primes between `a` and `b` (inclusive).

Input

1. `a` and `b` can be taken from command line or stdin (space seperated)
2. Assume `1 <= a <= b <=` 108

Output Just print the sum with a newline character.

Bonus Points

1. If the program accepts multiple ranges (print one sum on each line), you get extra points. :)
-
 The upper limit is too big to allow many interesting solutions (if they have to complete in reasonable time, at least). – hallvabo Jan 28 '11 at 9:13 @hallvabo You find inefficient solutions interesting? – Matthew Read Jan 28 '11 at 9:25 @hallvabo, That's ok. I don't think anyone minds an ineffcient solution. If other's object, i'll be more than happy to lower the limit – st0le Jan 28 '11 at 9:38 Just made and ran a not very optimised or concise version of the program in C#, using 1 to 10^8. Assuming my algorithm's correct, it ran in under 1m30s, and didn't overflow from a long. Seems like a fine upper limit to me! – Nellius Jan 28 '11 at 12:08 A quick easy check: sum of primes between 1 and 100 = 1060. – Nellius Jan 28 '11 at 12:50

J (41 32 chars):

``````h=:3 :'+/p:i.(_1 p:>:y)'
f=:-&h<:
``````

eg:

``````100 f 1
1060
``````
-

## Mathematica 7 (31 chars in plain text)

If PARI/GP solution allowed, then:

``````Plus@@Select[Range[a,b],PrimeQ]
``````
-
 What's your point? PARI/GP and Mathematica are fine programming languages. – Eelvex Jan 29 '11 at 8:28 @Eelvex, no, they break one of golf rules: using built-in specific highlevel functions. – Nakilon Jan 29 '11 at 9:19 I don't think there is such a rule. It's still an open matter when to use highlevel functions. See for ex. this meta question – Eelvex Jan 29 '11 at 9:42

### C (117 including NL)

``````main(a,b,s,j){
s=0,scanf("%d%d",&a,&b);
for(a+=a==1;a<=b;a++)
for(s+=a,j=2;j<a;)
s-=a%j++?0:(j=a);
printf("%d",s);
}
``````
-

C# (294 characters):

``````using System;class P{static void Main(){int a=int.Parse(Console.ReadLine()),b=int.Parse(Console.ReadLine());long t=0;for(int i=a;i<=b;i++)if(p(i))t+=i;Console.WriteLine(t);}static bool p(int n){if((n%2<1&&n!=2)||n<2)return 0>1;for(int i=3;i<=Math.Sqrt(n);i+=2)if(n%i==0)return 0>1;return 1>0;}}
``````
-
 You can make all your `int`s `long` and save a few characters: `long a=...,b=...,t=0,i=a;for(;i<=b;i++)`. This gets it to 288 chars. You can also let `p` return a long and just return either `0` or `n` and shorten the loop to `t+=p(i)`. 277 chars, then. – Joey Jun 19 '11 at 9:28

C# (183 characters)

``````using System;class P{static void Main(string[] a){long s=0,i=Math.Max(int.Parse(a[0]),2),j;for(;i<=int.Parse(a[1]);s+=i++)for(j=2;j<i;)if(i%j++==0){s-=i;break;}Console.WriteLine(s);}}
``````

This would be much shorter if it didn't have to check for 1, or if there was a better way to... In a more readable format:

``````using System;
class P
{
static void Main(string[] a)
{
long s = 0,
i = Math.Max(int.Parse(a[0]),2),
j;

for (; i <= int.Parse(a[1]);s+=i++)
for (j = 2; j < i; )
if (i % j++ == 0)
{
s -= i;
break;
}

Console.WriteLine(s);
}
}
``````
-
 I like how short this is, but I wonder how inefficient it would be when calculating up to 10^8! – Nellius Jan 28 '11 at 17:24 True, but efficiency wasn't in the rules! – NickLarsen Jan 28 '11 at 18:20 You know the compiler defaults numerics to 0 right? That'ld save you a couple more chars in there – jcolebrand Jan 29 '11 at 6:20 Gives error when compiled without it – NickLarsen Jan 29 '11 at 21:21 ...because it is never assigned before it is used (via `s -= i;` because thats just syntactic sugar for `s = s - i;` which tries to access `s` before setting it) – NickLarsen Jan 29 '11 at 21:28

PARI/GP (44 characters)

``````sum(x=nextprime(a),precprime(b),x*isprime(x))
``````
-
Shouldn't down voters give a reason for their -1? – Eelvex Jan 29 '11 at 8:27

# Perl, 62 chars

``````<>=~/\d+/;map\$s+=\$_*(1x\$_)!~/^1\$|(^11+)\1+\$/,\$&..\$';print\$s,\$/
``````

This one uses the prime number regex.

-

### 47 Characters

``````seq 1 100|factor|awk 'NF==2{s+=\$2}END{print s}'
``````

Edit: Just realized the sum overflows and is coerced as a double.

### 52 50 Characters

Here's a bit longer solution, but handles overflows aswell

``````seq 1 100|factor|awk NF==2{print\\$2}|paste -sd+|bc
``````
-
 tr is shorter than paste, and you can remove the single quotes (escape the `\$`). – Nabb Feb 4 '11 at 4:25 @Nabb, will fix it as soon as i get my hands on a *nix box, or you could do the honours. – st0le Feb 4 '11 at 4:28 @Nabb, can't get it to work, `tr` adds a trailing '+' at the end, fixing it will take more chars. – st0le Feb 6 '11 at 11:47 Ah, missed that. Although I think you can still change to `awk NF==2{print\\$2}` to save a byte on the longer solution (we won't accidentally run into brace expansion because there are no commas or `..`s). – Nabb Feb 6 '11 at 19:29 @Nabb, you're right. Done :) – st0le Feb 7 '11 at 4:25

``````c=u[2..];u(p:xs)=p:u[x|x<-xs,x`mod`p>0];s a b=(sum.filter(>=a).takeWhile(<=b))c
``````

`s 1 100 == 1060`

-
 This is code-golf! Why do you use such long names for your stuff? – FUZxxl Feb 3 '11 at 16:30 It's hard to find shorter names than c, u, s... The rest is language standard library. – J B Feb 7 '11 at 10:04

Ruby 1.9, 63 chars

``````require'prime';p=->a,b{Prime.each(b).select{|x|x>a}.inject(:+)}
``````

Use like this

``````p[1,100] #=> 1060
``````

Using the `Prime` class feels like cheating, but since the Mathematica solutions used built-in prime functions...

-

Common Lisp: (107 chars)

``````(flet((p(i)(loop for j from 2 below i never (= (mod i j) 0))))(loop for x from(read)to(read)when(p x)sum x))
``````

only works for starting points >= 1

-

## Python 3.1(270 229 205 chars):

``````from sys import *
p=[]
for i in range(int(argv[1]),int(argv[2])):
r=True
for j in range(2,int(argv[2])):
if i % j == 0and i != j:
r=False
if r:
p.append(i)
sum = 0
for n in p:
sum+=n
print(sum)
``````
-

## Perl, 103 chars

``````while(<>){(\$a,\$b)=split/ /;for(\$a..\$b){next if\$_==1;for\$n(2..\$_-1){\$_=0if\$_%\$n==0}\$t+=\$_;}print"\$t\n";}
``````

It'll accept multiple space separated lines and give the answer for each :D

-

## APL (25 characters)

``````+/((R≥⎕)^~R∊R∘.×R)/R←1↓⍳⎕
``````

This is a modification of a well-known idiom (see this page for an explanation) for generating a list of primes in APL.

Example:

``````      +/((R≥⎕)^~R∊R∘.×R)/R←1↓⍳⎕
⎕:
100
⎕:
1
1060
``````
-

C# 302

``````using System;namespace X{class B{static void Main(){long x=long.Parse(Console.ReadLine()),y=long.Parse(Console.ReadLine()),r=0;for(long i=x;i<=y;i++){if(I(i)){r+=i;}}Console.WriteLine(r);}static bool I(long n){bool b=true;if(n==1){b=false;}for(long i=2;i<n;++i){if(n%i==0){b=false;break;}}return b;}}}
``````
-

### Scala: 260

``````object P extends App{
def c(M:Int)={val p=(false::false::true::List.range(3,M+1).map(_%2!=0)).toArray
for(i<-(3 to M)
if p(i))
{var j=2*i
while(j<M){p(j)=false
j+=i}}
p}
val l=args.map(_.toInt)
val p=c(l(1))
println((l(0)to l(1)).filter(p).map(_.toLong).sum)}
``````

A self-written primes-sieve.

``````time scala P 3900000 4000000
25811704341

real    0m8.288s
user    0m6.968s
sys 0m0.456s
``````
-

## Python, 129

A little bit of sorcery:

``````x,y=map(int,input().split())
y+=1
a=range(y)
print sum(i for i in[[i for a[::i]in[([0]*y)[::i]]][0]for i in a[2:]if a[i]]if i>=x)
``````
-
 -1 (Well I don't have enough rep to downvote yet) This is invalid in Python 2 or 3, you can't expect input to conveniently contain quotation marks for you. Change to raw_input or use python 3 plz – jamylak Jul 30 '12 at 6:21

Python: 110 chars

``````l,h=map(int,raw_input().split())
print sum(filter(lambda p:p!=1 and all(p%i for i in range(2,p)),range(l,h)))
``````
-
 This is not inclusive. – jamylak Jul 30 '12 at 6:23

## In Q (95):

``````d:{sum s:{if[2=x;:x];if[1=x;:0];\$[0=x mod 2;0;0=min x mod 2+til floor sqrt x;0;x]}each x+til y}
``````

Sample Usage:

``````q)d[1;100]
1060
``````
-

# Factor -> 98

``````:: s ( a b -- n )
:: i ( n -- ? )
n 1 - 2 [a,b] [ n swap mod 0 > ] all? ;
a b [a,b] [ i ] filter sum ;
``````

Output:

``````( scratchpad ) 100 1000 s

--- Data stack:
75067
``````
-

## Mathematica, 27

Predefined `a` and `b`:

``````a~Range~b~Select~PrimeQ//Tr
``````

As a function (also 27):

``````Tr[Range@##~Select~PrimeQ]&
``````
-

## Normal Task (Python 3): 95 chars

``````a,b=map(int,input().split())
r=range
print(sum(1%i*all(i%j for j in r(2,i))*i for i in r(a,b+1)))
``````

## Bonus Task (Python 3): 119 chars

``````L=iter(map(int,input().split()))
r=range
for a,b in zip(L,L):print(sum(1%i*all(i%j for j in r(2,i))*i for i in r(a,b+1)))
``````
-