# Additive Primes amongst first x Primes

• Numbers which have exactly 2 divisors are called Prime numbers.

• Numbers which are prime and their sum of digits is also a prime number are called Additive Primes

Given an integer x, compute all the additive primes amongst the first x prime numbers, with 2 being considered both the first prime and additive prime number. The numbers are represented in base 10.

## Rules:

• The output consists of all the additive primes amongst the first x primes
• 0 < x < 151, for this challenge, for functionality purposes
• Since the additive primes are all integers, decimals are not allowed (e.g.: you should output 2, not 2.0) and they must not be displayed as a fraction.

## Examples:

10 -> 2 3 5 7 11 23 29

Explanation:

The first 10 primes are 2 3 5 7 11 13 17 19 23 29, and only 2 3 5 7 11 23 29 have their sum of digits prime numbers, those being, respectively 2,3,5,7,2,5,11, so they are additive primes

Following the explanation from example 1, other test cases may be:

2 -> 2 3

25 -> 2 3 5 7 11 23 29 41 43 47 61 67 83 89

7 -> 2 3 5 7 11


var QUESTION_ID=112088,OVERRIDE_USER=59487;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left;font-family:"Helvetica Neue"}table thead{font-weight:700;font-family:"Helvetica Neue"}table td{padding:5px;font-family:"Helvetica Neue"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

NOTE: Please read the newly-edited rule 1, it brings changes to the output format slightly

Your code should be as short as possible, since this is , so the shortest answer in bytes wins. Good luck!

• That's fine. I'd recommend waiting around 24 hours though, because every time you accept the answer they get 15 rep, but they lose it when you un-accept. It's somewhat frustrating sometimes to ride the rollercoaster and continuously lose and gain rep. Mar 5, 2017 at 15:19

# Röda, 136 135 bytes

f n{P=[2]S=[2]seq 3,863|{|i|{P|{P+=i;s=0;((""..i)/"")|parseInteger _|s+=_;S+=i if[s in P and not(i in S)]}if{|p|[i%p>0]}_}if[#P<n]}_;S}


Try it online!

It's a function that returns the requested additive primes.

Usage: main { f(25) | print ap for ap } The code uses version 0.12, which is in branch roda-0.12.

Ungolfed:

function f(n) {
primes := [2]
ultraprimes := [2]
seq(3, 863) | for i do
break if [ #primes = n ]
if [ i%p != 0 ] for p in primes do
primes += i
sum := 0
((""..i)/"") | parseInteger _ | sum += digit for digit
ultraprimes += i if [ sum in primes and not (i in ultraprimes) ]
done
done
ultraprimes
}

• Nice language! You made this yourself a long time ago it looks like? 10/10, looks pretty cool. Mar 5, 2017 at 16:14
• Neat language! How do you run the program? Mar 5, 2017 at 16:26
• Was just about to ask the same thing. Although I looked over the documentation, I cannot run or compile the source at all. What is your approach? Mar 5, 2017 at 16:40
• @KritixiLithos @Xcoder123 It requires Java 8 and Gradle. The version I use in this answer is 0.12 (in its own branch). The repository must be cloned recursively. To make a runnable jar, invoke gradle fatJar. Do you get any errors when compiling? Mar 5, 2017 at 16:43
• @fergusq Running gradle fatJar doesn't seem to create a jar for me Mar 5, 2017 at 16:45

## Pyke, 9 7 bytes

~p>#Yss


Try it online!

The single byte is_prime was only pushed 3 hours ago. Github commit.

~p      -    All the prime numbers
>     -   first input of them
#Yss -  filter(^)
Y   -     digits(^)
s  -    sum(^)
s -   is_prime(^)

• Did you just edit your language to suit this challenge? :D Mar 5, 2017 at 17:43
• so... s means is_prime on numbers, and sum on lists? Mar 5, 2017 at 20:15
• @ConorO'Brien yes, I overload it for lists and integers
– Blue
Mar 5, 2017 at 21:36
• @Džuris no, I've been meaning to for a while because I haven't had a single node for doing prime checking, only factorising into primes and divisors. Before I would have had to do _P which is 1 byte longer in this case
– Blue
Mar 5, 2017 at 21:38
• a new contender for "youngest language feature to win a challenge"? under the wire by ~2 hours? Mar 5, 2017 at 22:06

## Python 2, 124 118 bytes

With help from Riker:

n,f,P=input(),filter,lambda n:all(n%i for i in range(2,n))
f(lambda x:P(sum(map(int,x)))&P(x),f(P,range(2,n*n))[:n])


Original:

n,o,c,P=input(),0,2,lambda n:all(n%i for i in range(2,n))
while o<n:
o+=P(c)
if P(sum(map(int,c)))and P(c):print c
c+=1


Checking primality in Python ain't fun.

• I (read: got conor to write cool J code for me) have tested this with 9n, doesn't work. :/ n**2 does work, but at a cost of 1 byte. Mar 5, 2017 at 17:58
• Try n*n for n**2 Mar 5, 2017 at 17:59

# Perl 6, 53 bytes

{grep *.comb.sum.is-prime,grep(*.is-prime,0..*)[^$_]}  Try it ## Expanded: { grep *.comb.sum.is-prime, # find the ultra primes from: grep( *.is-prime, # find the primes 0..* # from all integers )[ ^$_ ]             # grab only the first x primes
}


If this challenge were changed so that you took the first x ultraprimes this could be shortened to just

{grep({($_&.comb.sum).is-prime},0..*)[^$_]}


# Python 2, 96 87 bytes

p=-input(),0;m=k=1
while sum(p):
m*=k*k;k+=1;p+=m%k,
if m%k*p[int(k,36)%35]:print k


Thanks to @xnor for golfing off 9 bytes!

Try it online!

• Looks like using a list of indicator variables is shorter.
– xnor
Mar 6, 2017 at 1:52
• The digit sum can be done shorter as is int(k,36)%35. All the inputs will be small enough that this suffices.
– xnor
Mar 6, 2017 at 2:12
• More golfing
– xnor
Mar 6, 2017 at 2:23
• Wow! I'm not sure how I thought of a Boolean dict but not a Boolean tuple (hindsight is 20/20), but sum(p) and int(k,36)%35 are something else... Thanks! Mar 6, 2017 at 2:36

## Mathematica, 61 47 bytes

Prime@Range@#~Select~PrimeQ@*Tr@*IntegerDigits&

• Not entirely familiar with Mathematica's shorthand syntaxes - what's that @*? The * doesn't look like it's in the right place to be multiplication? Mar 6, 2017 at 3:23
• @numbermaniac it's function composition. f@*g is essentially f@g@##&. Mar 6, 2017 at 7:08

# Jelly, 10 bytes

ÆNDS$€ĖÆPM  Try it online! ### How? A slightly different approach... ÆNDS$€ĖÆPM - Main link: n (>0)           e.g. 10
ÆN         - nth prime number                 29
€     - for each in range(1,nth prime)   [1,    2,    3,   ..., 27,    28,     29]
$- last two links as a monad D - decimal digit list [[1], [2], [3], ...,[2,7], [2,8], [2,9]] S - sum [1, 2, 3, ..., 9, 10, 11] Ė - enumerate [[1,1],[2,2],[3,3],...,[9,27],[10,28],[11,29]] ÆP - is prime? (vectorises) [[0,0],[1,1],[1,1],...,[0,1], [0,0], [1,1]] M - indices of maximal elements [ 2, 3, ..., 29]  • Nice use of Ė. Mar 5, 2017 at 16:12 # 05AB1E, 9 bytes ÝØ¨vySOp—  Uses the CP-1252 encoding. Try it online! # Jelly, 11 bytes ÆN€DS$ÆP$Ðf  Try it online! Explanation: ÆN€DS$ÆP$Ðf Main link (args: z) ÆN€ Generate first z primes. DS$      Take the digital sum.
ÆP    Check if it's prime.
$Join last two links and make a monad. Ðf Only keep elements which conform to the criterion above. I got outgolfed. # MATL, 15 13 bytes 2 bytes saved thanks to @Luis :Yq"@V!UsZp?@  Try it at MATL Online Explanation  % Implicitly grab input as a number (N) : % Create an array [1...N] Yq % Get the k-th prime for each element k in that array " % For each element in this list @ % Get the current element V!U % Break it into digits s % Sum up the digits Zp % Determine if this is a prime number ?@ % If it is, push the value to the stack % Implicit end of for loop and implicit display of the stack  • @LuisMendo Ah! I knew there was some way to shorten that first part. Thanks Mar 11, 2017 at 0:30 # Bash + coreutils, 97 bytes p()(factor$1|wc -w)
for((;++n,c<$1;)){((p$n-2||(c++,p $[n%10+n/10%10+n/100]-2)))||echo$n;}


Try it online!

# Ohm, 10 bytes (CP437)

@▓_π;░_}Σp


This would be much shorter if I had vectorization or a component for the first N primes, but alas, I did not before this challenge (but I do now!).

Explanation:

@▓_π;░_}Σp    Main wire, arguments: a

@▓  ;         Map...over the range (1..n)
_π            nth prime
░        Select from ToS where...
_}Σ       The sum of all digits
p      is prime


# PowerShell, 120 bytes

for($n=$args[0];$n){for(;'1'*++$i-notmatch($s='^(?!(..+)\1+$)..')){}if('1'*([char[]]"$i"-join'+'|iex)-match$s){$i};$n--}


Try it online!

Prime checking in PowerShell sucks.

The outer for loop goes from input $n down to 0. In the inner loop, we use a prime generator on $i, then check if the digit-sum (-join'+'|iex) is also a prime. If so, we put $i on the pipeline. In either case, we decrement $n-- and the outer for loop continues. The resulting $is are gathered from the pipeline and an implicit Write-Output happens at program completion. # Bash + GNU utilities + bsd-games package, 69 primes 2|sed -rn 'h;s/./ + &/g;s/.*/expr &|factor/e;/\w\s/!{x;p};'$1q


# Pari/GP, 59 bytes

f(x)=[p|p<-vector(x,i,prime(i)),isprime(vecsum(digits(p)))]


Try it online!

# MATL, 13 bytes

:YqtFYA!XsZp)


Try it at MATL Online!

### Explanation

:      % Range [1 2 ... n], where n is implicit input
Yq     % Array of first n prime numbers
t      % Duplicate
FYA    % Convert to decimal digits. Gives a matrix, where each original
% number corresponds to a row. Left-pads with zeros if needed
!Xs    % Sum of rows
Zp     % Is prime? (element-wise)
)      % Use as logical index into the array of the first n prime numbers
% Implicitly display


# Husk, 8 bytes

fȯṗΣd↑İp


Try it online!

# Japt, 12 bytes

Èj}jU fÈìx j


Try it

# Factor + math.primes math.unicode math.text.utils, 47 bytes

[ nprimes [ 1 digit-groups Σ prime? ] filter ]


Try it online!

## Explanation:

It's a quotation (anonymous function) that takes an integer from the data stack as input and leaves a sequence of integers on the data stack as output.

• nprimes Obtain a list of the first n primes.
• [ ... ] filter Take elements from the list that match a predicate.
• 1 digit-groups Obtain a list of digits from an integer.
• Σ Sum a sequence.
• prime? Is it prime?