Primes whose sum of digits is 25: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(30 intermediate revisions by 23 users not shown)
Line 12:
::: <big>(997 &nbsp; &le; &nbsp; '''n''' &nbsp; &le; &nbsp; 1,111,111,111,111,111,111,111,111). </big>
<br><br>
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">F is_prime(a)
I a == 2
R 1B
I a < 2 | a % 2 == 0
R 0B
L(i) (3 .. Int(sqrt(a))).step(2)
I a % i == 0
R 0B
R 1B
 
F digit_sum(=n)
V result = 0
L n != 0
result += n % 10
n I/= 10
R result
 
V c = 0
L(n) 5000
I digit_sum(n) == 25 & is_prime(n)
c++
print(‘#4’.format(n), end' I c % 6 == 0 {"\n"} E ‘ ’)
print()
print(‘Found ’c‘ primes whose sum of digits is 25’)</syntaxhighlight>
 
{{out}}
<pre>
997 1699 1789 1879 1987 2689
2797 2887 3499 3697 3769 3877
3967 4597 4759 4957 4993
Found 17 primes whose sum of digits is 25
</pre>
 
=={{header|Action!}}==
{{libheader|Action! Sieve of Eratosthenes}}
<syntaxhighlight lang="action!">INCLUDE "H6:SIEVE.ACT"
 
BYTE FUNC SumOfDigits(INT x)
BYTE s,d
 
s=0
WHILE x#0
DO
d=x MOD 10
s==+d
x==/10
OD
RETURN (s)
 
PROC Main()
DEFINE MAX="4999"
BYTE ARRAY primes(MAX+1)
INT i,count=[0]
 
Put(125) PutE() ;clear the screen
Sieve(primes,MAX+1)
FOR i=2 TO MAX
DO
IF primes(i)=1 AND SumOfDigits(i)=25 THEN
PrintI(i) Put(32)
count==+1
FI
OD
PrintF("%E%EThere are %I primes",count)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Primes_which_sum_of_digits_is_25.png Screenshot from Atari 8-bit computer]
<pre>
997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993
 
There are 17 primes
</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN # find primes whose digits sum to 25 #
# returns a sieve of primes up to n #
PROC eratosthenes = ( INT n )[]BOOL:
BEGIN
[ 1 : n ]BOOL p;
p[ 1 ] := FALSE; p[ 2 ] := TRUE;
FOR i FROM 3 BY 2 TO n DO p[ i ] := TRUE OD;
FOR i FROM 4 BY 2 TO n DO p[ i ] := FALSE OD;
FOR i FROM 3 BY 2 TO ENTIER sqrt( n ) DO
IF p[ i ] THEN FOR c FROM i * i BY i + i TO n DO p[ c ] := FALSE OD FI
OD;
p
END # eratosthenes # ;
# show all sum25 primes below 5000 #
PR read "primes.incl.a68" PR
INT max show sum25 = 4999;
[]BOOL prime = eratosthenes(PRIMESIEVE max show sum25 )4999;
INT p25 count := 0;
FOR n TO maxUPB show sum25prime DO
IF prime[ n ] THEN
# have a prime, check for a sum25 prime #
Line 47 ⟶ 111:
FI
OD;
print( ( newline, "Found ", whole( p25 count, 0 ), " sum25 primes below ", whole( maxUPB show sum25prime + 1, 0 ), newline ) )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 59 ⟶ 123:
Uses the [[Miller–Rabin_primality_test#ALGOL 68|Miller Rabin primality test]] and the pow mod procedure from [[ALGOL_68/prelude#prelude.2Fpow_mod.a68|prelude/pow_mod]]<br>
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<langsyntaxhighlight lang="algol68">BEGIN
PROC pow mod = (LONG LONG INT b,in e, modulus)LONG LONG INT: (
LONG LONG INT sq := b, e := in e;
Line 112 ⟶ 176:
sum25( 0, 25 );
print( ( "There are ", whole( p25 count, 0 ), " sum25 primes that contain no zeroes", newline ) )
END</langsyntaxhighlight>
{{out}}
Note that ALGOL 68G under Windows is fully interpreted so runtime is not of the same order as the Phix and Go samples,. underUnder Linux with optimisation and compilation., it mayshould be faster than under Windows.
<pre>
There are 1525141 sum25 primes that contain no zeroes
Line 120 ⟶ 184:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin % find some primes whose digits sum to 25 %
% sets p( 1 :: n ) to a sieve of primes up to n %
procedure Eratosthenes ( logical array p( * ) ; integer value n ) ;
Line 159 ⟶ 223:
write( i_w := 1, s_w := 0, "Found ", pCount, " sum25 primes below ", MAX_NUMBER + 1 )
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 169 ⟶ 233:
===Functional===
Not fast. This approach takes over 20 seconds here.
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 330 ⟶ 394:
end tell
return ys
end takeWhile</langsyntaxhighlight>
{{Out}}
<pre>[997,1699,1789,1879,1987,2689,2797,2887,3499,3697,3769,3877,3967,4597,4759,4957,4993]</pre>
Line 338 ⟶ 402:
Primes with silly properties are getting a bit tedious. But hey. This takes just under 0.02 seconds.
 
<langsyntaxhighlight lang="applescript">on sieveOfEratosthenes(limit)
script o
property numberList : {missing value}
Line 347 ⟶ 411:
end repeat
repeat with positionn from 2 to (limit ^ 0.5) div 1
if (item positionn of o's numberList is not missing valuen) then
repeat with multiple from positionn * positionn to limit by positionn
set item multiple of o's numberList to missing value
end repeat
Line 357 ⟶ 421:
return o's numberList's numbers
end sieveOfEratosthenes
 
on sumOfDigits(n) -- n assumed to be a positive decimal integer.
set sum to n mod 10
set n to n div 10
repeat until (n = 0)
set sum to sum + n mod 10
set n to n div 10
end repeat
return sum
end sumOfDigits
 
on numbersWhoseDigitsSumTo(numList, targetSum)
Line 364 ⟶ 439:
end script
repeat with thisNumbern in o's numberList
setif (sumOfDigits(n) = targetSum) then set end of o's output to thisNumbern's contents
set digitSum to n mod 10
repeat until n is 0
set n to n div 10
set digitSum to digitSum + n mod 10
end repeat
if (digitSum = targetSum) then set end of o's output to thisNumber's contents
end repeat
Line 378 ⟶ 447:
 
-- Task code:
set primesBelow5000 toreturn numbersWhoseDigitsSumTo(sieveOfEratosthenes(4999), 25)</syntaxhighlight>
set thoseWhoseDigitsSumTo25 to numbersWhoseDigitsSumTo(primesBelow5000, 25)</lang>
 
{{output}}
<langsyntaxhighlight lang="applescript">{997, 1699, 1789, 1879, 1987, 2689, 2797, 2887, 3499, 3697, 3769, 3877, 3967, 4597, 4759, 4957, 4993}</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">primes: select 1..5000 => prime?
 
loop split.every: 3 select primes 'p [25 = sum digits p] 'a ->
print map a => [pad to :string & 5]</syntaxhighlight>
 
{{out}}
 
<pre> 997 1699 1789
1879 1987 2689
2797 2887 3499
3697 3769 3877
3967 4597 4759
4957 4993</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f PRIMES_WHICH_SUM_OF_DIGITS_IS_25.AWK
BEGIN {
Line 416 ⟶ 500:
return(1)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 422 ⟶ 506:
Prime numbers 1-5000 whose digits sum to 25: 17
</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
function isprime(num)
for i = 2 to int(sqr(num))
if (num mod i = 0) then return False
next i
return True
end function
 
function digit_sum(num)
sum25 = 0
for j = 1 to length(num)
sum25 += int(mid(string(num),j,1))
next j
return sum25
end function
 
inicio = 1: final = 5000
total = 0
for i = inicio to final
if isprime(i) and (digit_sum(i) = 25) then
total += 1
print i; " ";
end if
next i
print chr(13) + chr(13)
print "Se encontraron "; total; " primos sum25 por debajo de "; final
end
</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
 
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
 
Line 475 ⟶ 596:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993</pre>
Line 482 ⟶ 603:
{{libheader|GMP}}
Stretch goal solved the same way as Phix and Go.
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <chrono>
#include <iomanip>
Line 560 ⟶ 681:
<< std::chrono::duration<double>(end - start).count() << "s\n";
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 578 ⟶ 699:
Exit code: 0
</pre>
 
=={{header|D}}==
{{trans|C}}
<syntaxhighlight lang="d">import std.bigint;
import std.stdio;
 
bool isPrime(BigInt n) {
if (n < 2) {
return false;
}
 
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
 
auto i = BigInt(5);
while (i * i <= n) {
if (n % i == 0){
return false;
}
i += 2;
 
if (n % i == 0){
return false;
}
i += 4;
}
 
return true;
}
 
int digitSum(BigInt n) {
int result;
while (n > 0) {
result += n % 10;
n /= 10;
}
return result;
}
 
void main() {
for (auto n = BigInt(2); n < 5_000; n++) {
if (n.isPrime && n.digitSum == 25) {
write(n, ' ');
}
}
writeln;
}</syntaxhighlight>
{{out}}
<pre>997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993 </pre>
 
=={{header|Delphi}}==
Line 583 ⟶ 757:
{{libheader| PrimTrial}}
{{Trans|Ring}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Primes_which_sum_of_digits_is_25;
 
Line 622 ⟶ 796:
end;
readln;
end.</langsyntaxhighlight>
{{out}}
<pre> 997 1699 1789 1879 1987
Line 630 ⟶ 804:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Primes to 5000 who's sum of digits is 25. Nigel Galloway: April 1st., 2021
let rec fN g=function n when n<10->n+g=25 |n->fN(g+n%10)(n/10)
primes32()|>Seq.takeWhile((>)5000)|>Seq.filter fN|>Seq.iter(printf "%d "); printfn ""
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 641 ⟶ 815:
=={{header|Factor}}==
{{works with|Factor|0.99 2021-02-05}}
<langsyntaxhighlight lang="factor">USING: kernel lists lists.lazy math math.primes.lists prettyprint ;
 
: digit-sum ( n -- sum )
Line 648 ⟶ 822:
: lprimes25 ( -- list ) lprimes [ digit-sum 25 = ] lfilter ;
 
lprimes25 [ 5,000 < ] lwhile [ . ] leach</langsyntaxhighlight>
{{out}}
<pre style="height:14em">
Line 672 ⟶ 846:
=={{header|Forth}}==
{{works with|Gforth}}
<langsyntaxhighlight lang="forth">: prime? ( n -- ? ) here + c@ 0= ;
: notprime! ( n -- ) here + 1 swap c! ;
 
Line 719 ⟶ 893:
 
5000 .prime25
bye</langsyntaxhighlight>
 
{{out}}
Line 727 ⟶ 901:
3769 3877 3967 4597 4759 4957 4993
Count: 17
</pre>
 
 
=={{header|FreeBASIC}}==
{{trans|AWK}}
<syntaxhighlight lang="freebasic">
Function isprime(num As Ulongint) As Boolean
For i As Integer = 2 To Sqr(num)
If (num Mod i = 0) Then Return False
Next i
Return True
End Function
 
Function digit_sum(num As Integer) As Integer
Dim As Integer sum25 = 0
For j As Integer = 1 To Len(num)
sum25 += Val(Mid(Str(num),j,1))
Next j
Return sum25
End Function
 
Dim As Integer inicio = 1, final = 5000, total = 0
For i As Integer = inicio To final
If (isprime(i)) And (digit_sum(i) = 25) Then
total += 1
Print Using " ####"; i;
If (total Mod 9) = 0 Then Print
End If
Next i
Print !"\n\nSe encontraron"; total; " primos sum25 por debajo de"; finalSleep
</syntaxhighlight>
{{out}}
<pre>
997 1699 1789 1879 1987 2689 2797 2887 3499
3697 3769 3877 3967 4597 4759 4957 4993
 
Se encontraron 17 primos sum25 por debajo de 5000
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">println[select[primes[2,4999], {|x| sum[integerDigits[x]] == 25}]]</syntaxhighlight>
{{out}}
<pre>
[997, 1699, 1789, 1879, 1987, 2689, 2797, 2887, 3499, 3697, 3769, 3877, 3967, 4597, 4759, 4957, 4993]
</pre>
 
Line 732 ⟶ 950:
{{libheader|GMP(Go wrapper)}}
This uses the Phix routine for the stretch goal though I've had to plug in a GMP wrapper to better the Phix time. Using Go's native big.Int, the time was slightly slower than Phix at 1 minute 28 seconds.
<langsyntaxhighlight lang="go">package main
 
import (
Line 831 ⟶ 1,049:
fmt.Println("\nThere are", commatize(n), "primes whose digits sum to 25 and include no zeros.")
fmt.Printf("\nTook %s\n", time.Since(start))
}</langsyntaxhighlight>
 
{{out}}
Line 844 ⟶ 1,062:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Bifunctor (second)
import Data.List (replicate)
import Data.List.Split (chunksOf)
Line 880 ⟶ 1,098:
 
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>)</langsyntaxhighlight>
{{Out}}
<pre>17 primes (< 5000) with decimal digits totalling 25:
Line 889 ⟶ 1,107:
3967 4597 4759 4957
4993</pre>
 
=={{header|J}}==
<syntaxhighlight lang="j"> (#~ 25 = +/@("."0@":)"0) p: i. _1 p: 5000
997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993</syntaxhighlight>
 
=={{header|Java}}==
{{trans|Kotlin}}
<syntaxhighlight lang="java">import java.math.BigInteger;
 
public class PrimeSum {
private static int digitSum(BigInteger bi) {
int sum = 0;
while (bi.compareTo(BigInteger.ZERO) > 0) {
BigInteger[] dr = bi.divideAndRemainder(BigInteger.TEN);
sum += dr[1].intValue();
bi = dr[0];
}
return sum;
}
 
public static void main(String[] args) {
BigInteger fiveK = BigInteger.valueOf(5_000);
BigInteger bi = BigInteger.valueOf(2);
while (bi.compareTo(fiveK) < 0) {
if (digitSum(bi) == 25) {
System.out.print(bi);
System.out.print(" ");
}
bi = bi.nextProbablePrime();
}
System.out.println();
}
}</syntaxhighlight>
{{out}}
<pre>997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993 </pre>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
Line 1,021 ⟶ 1,274:
 
return main();
})();</langsyntaxhighlight>
<pre>997 1699 1789 1879 1987
2689 2797 2887 3499 3697
3769 3877 3967 4597 4759
4957 4993</pre>
 
=={{header|jq}}==
'''Works with [[#jq|jq]] '''<br>
'''Works with gojq, the Go implementation of jq'''
 
The stretch goal is currently beyond the practical capabilities of both the C and Go-based implementations of jq,
so only a simple solution to the primary task is shown here.
 
A suitable definition of `is_prime` may be found at [[Erd%C5%91s-primes#jq]] and is therefore not repeated here.
 
'''Preliminaries'''
<syntaxhighlight lang="jq">def digits: tostring | explode | map( [.]|implode|tonumber);
 
def emit_until(cond; stream): label $out | stream | if cond then break $out else . end;</syntaxhighlight>
'''The Task'''
<syntaxhighlight lang="jq"># Output: primes whose decimal representation has no 0s and whose sum of digits is $sum > 2
def task($sum):
# Input: array of digits
def nozeros: select(all(.[]; . != 0));
range(3;infinite;2)
| select(digits | (.[-1] != 5 and nozeros and (add == $sum)) )
| select(is_prime);
emit_until(. >= 5000; task(25) )</syntaxhighlight>
{{out}}
<pre>
997
1699
1789
1879
1987
2689
2797
2887
3499
3697
3769
3877
3967
4597
4759
4957
4993
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Primes
 
let
Line 1,043 ⟶ 1,340:
println("\nTotal found: $pcount")
end
</langsyntaxhighlight>{{out}}
<pre>
Primes with digits summing to 25 between 0 and 5000:
Line 1,051 ⟶ 1,348:
=== Stretch goal ===
{{trans|Phix}}
<langsyntaxhighlight lang="julia">using Primes, Formatting
 
function sum25(p::String, rm, res)
Line 1,068 ⟶ 1,365:
@time println("There are ", format(sum25("", 25, 0), commas=true),
" primes whose digits sum to 25 without any zero digits.")
</langsyntaxhighlight>{{out}}
<pre>
There are 1,525,141 primes whose digits sum to 25 without any zero digits.
Line 1,075 ⟶ 1,372:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">import java.math.BigInteger
 
fun digitSum(bi: BigInteger): Int {
Line 1,101 ⟶ 1,398:
}
println()
}</langsyntaxhighlight>
{{out}}
<pre>997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993 </pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Primes which sum of digits is 25
 
# # Variables:
#
integer MAXN=5000 SUM=25
 
# # Functions:
#
# # Function _sumdigits(n, sum) - return 1 if sum of n's digits = sum
#
function _sumdigits {
typeset _n ; integer _n=$1
typeset _sum ; integer _sum=$2
typeset _i _dsum ; integer _i _dsum=0
 
for ((_i=0; _i<${#_n}; _i++)); do
(( _dsum+=${_n:_i:1} ))
done
return $(( _dsum == _sum ))
}
 
# # Function _isprime(n) return 1 for prime, 0 for not prime
#
function _isprime {
typeset _n ; integer _n=$1
typeset _i ; integer _i
 
(( _n < 2 )) && return 0
for (( _i=2 ; _i*_i<=_n ; _i++ )); do
(( ! ( _n % _i ) )) && return 0
done
return 1
}
 
######
# main #
######
 
for ((i=3; i<$MAXN; i++)); do
_isprime ${i} || _sumdigits ${i} $SUM || printf "%d " ${i}
done
echo
</syntaxhighlight>
{{out}}<pre>
997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993 </pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Select[Prime[Range@PrimePi[4999]], IntegerDigits /* Total /* EqualTo[25]]</syntaxhighlight>
{{out}}
<pre>{997, 1699, 1789, 1879, 1987, 2689, 2797, 2887, 3499, 3697, 3769, 3877, 3967, 4597, 4759, 4957, 4993}</pre>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">// find primes using the sieve of eratosthenes
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode
def find_primes(upper_bound)
Line 1,144 ⟶ 1,496:
end if
end for
println</langsyntaxhighlight>
{{out}}
<pre>997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993 </pre>
 
=={{header|Nim}}==
===Task===
<syntaxhighlight lang="nim">import strutils, sugar
 
func isPrime(n: Natural): bool =
if n < 2: return false
if n mod 2 == 0: return n == 2
if n mod 3 == 0: return n == 3
var d = 5
while d * d <= n:
if n mod d == 0: return false
inc d, 2
if n mod d == 0: return false
inc d, 4
result = true
 
func digitSum(n: Natural): int =
var n = n
while n != 0:
result += n mod 10
n = n div 10
 
let result = collect(newSeq):
for n in countup(3, 5000, 2):
if digitSum(n) == 25 and n.isPrime: n
 
for i, n in result:
stdout.write ($n).align(4), if (i + 1) mod 6 == 0: '\n' else: ' '
echo()</syntaxhighlight>
 
{{out}}
<pre> 997 1699 1789 1879 1987 2689
2797 2887 3499 3697 3769 3877
3967 4597 4759 4957 4993 </pre>
 
===Stretch goal===
{{trans|Julia}}
{{libheader|bignum}}
<syntaxhighlight lang="nim">import std/monotimes, strformat, strutils
import bignum
 
func sum25(p: string; rm, res: Natural): Natural =
result = res
if rm == 0:
if p[^1] in "1379" and probablyPrime(newInt(p), 25) != 0:
inc result
else:
for i in 1..min(rm, 9):
result = sum25(p & chr(i + ord('0')), rm - i, result)
 
let t0 = getMonoTime()
let count = $sum25("", 25, 0)
echo &"There are {count.insertSep()} primes whose digits sum to 25 without any zero digits."
echo "\nExecution time: ", getMonoTime() - t0</syntaxhighlight>
 
{{out}}
<pre>There are 1_525_141 primes whose digits sum to 25 without any zero digits.
 
Execution time: (seconds: 12, nanosecond: 182051288)</pre>
 
=={{header|Pascal}}==
added only strechted goal.Generating the combination of the digits for the numbers and afterwards generating the [[Permutations with some identical elements]]<BR>
Now seting one digit out of 1,3,7,9 to the end and permute the rest of the digits in front.<BR>So much less numbers have to be tested.10.5e6 instead of 16.4e6.Generating of the numbers is reduced in the same ratio.
<langsyntaxhighlight lang="pascal">program Perm5aus8;
//formerly roborally take 5 cards out of 8
{$IFDEF FPC}
Line 1,356 ⟶ 1,768:
mpz_clear(z);
END.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,383 ⟶ 1,795:
=={{header|Perl}}==
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 1,392 ⟶ 1,804:
is_prime($_) and 25 == sum(split '', $_) and push @p25, $_ for 1..$limit;
say @p25 . " primes < $limit with digital sum 25:\n" . join ' ', @p25;
</syntaxhighlight>
</lang>
{{out}}
<pre>17 primes < 5000 with digital sum 25:
Line 1,398 ⟶ 1,810:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">sum25</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_sub</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">),</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">))=</span><span style="color: #000000;">25</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_primes_le</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5000</span><span style="color: #0000FF;">),</span><span style="color: #000000;">sum25</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">),</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">))</span>
<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;">"%d sum25 primes less than 5000 found: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">),</span><span style="color: #000000;">r</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,410 ⟶ 1,822:
===Stretch goal===
{{libheader|Phix/mpfr}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">includewithout</span> <span style="color: #7060A8008080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">ejs</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">(),</span> <span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span>
<span style="color: #7060A8004080;">mpz</span> <span style="color: #000000;">pz</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">sum25</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">rem</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">rem</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">[$],</span><span style="color: #008000;">"1379"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- (saves 13s)</span>
<span style="color: #0000007060A8;">mpz_set_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pz</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #0000007060A8;">mpz_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pz</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()></span><span style="color: #000000;">t1</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">progress</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d, %s..."</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span>
Line 1,437 ⟶ 1,850:
<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;">"There are %,d sum25 primes that contain no zeroes\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sum25</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">25</span><span style="color: #0000FF;">))</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,443 ⟶ 1,856:
"1 minute and 27s"
</pre>
Note this works under pwa/p2js but you would get to stare at a blank screen for 8&frac12; minutes with 100% cpu, hence it has been marked "without js".
 
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">'''Primes with a decimal digit sum of 25'''
 
from itertools import takewhile
Line 1,519 ⟶ 1,933:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>17 primes below 5000 with a decimal digit sum of 25:
Line 1,528 ⟶ 1,942:
3967 4597 4759 4957
4993</pre>
 
=={{header|Quackery}}==
 
<code>eratosthenes</code> and <code>isprime</code> are defined at [[Sieve of Eratosthenes#Quackery]].
 
<syntaxhighlight lang="Quackery"> 5000 eratosthenes
[ 0
[ over while
swap 10 /mod
rot + again ]
nip ] is digitsum ( n --> n )
 
[] 5000 times
[ i^ isprime not if done
i^ digitsum 25 = if
[ i^ join ] ]
echo
</syntaxhighlight>
 
{{out}}
 
<pre>[ 997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993 ]</pre>
 
=={{header|Raku}}==
<syntaxhighlight lang="raku" perl6line>unit sub MAIN ($limit = 5000);
say "{+$_} primes < $limit with digital sum 25:\n{$_».fmt("%" ~ $limit.chars ~ "d").batch(10).join("\n")}",
with ^$limit .grep: { .is-prime and .comb.sum == 25 }</langsyntaxhighlight>
{{out}}
<pre>17 primes < 5000 with digital sum 25:
Line 1,543 ⟶ 1,980:
:* &nbsp; the number of columns shown per line &nbsp; ('''COLS''')
;* &nbsp; the target sum &nbsp; ('''TARGET''')
<langsyntaxhighlight lang="rexx">/*REXX pgm finds and displays primes less than HI whose decimal digits sum to TARGET.*/
parse arg hi cols target . /*obtain optional argument from the CL.*/
if hi=='' | hi=="," then hi= 5000 /*Not specified? Then use the default.*/
Line 1,550 ⟶ 1,987:
call genP /*build array of semaphores for primes.*/
w= 10 /*width of a number in any column. */
@primestitle= ' primes that are < ' commas(hi) " and whose decimal digits sum to " ,
commas(target)
if cols>0 then say ' index │'center(@primes commas(target), 1 + cols*(w+1) )
if cols>0 then say '───────┼ index │'center("" title, 1 + cols*(w+1), '─' )
if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─')
primesT= 0; idx= 1 /*define # target primes found & index.*/
found= 0; idx= 1 /*define # target primes found and IDX.*/
$= /*list of target primes found (so far).*/
do j=1 for #; y= @.j /*examine all the primes generated. */
if sumDigs(y@.j)\==target then iterate /*Is sum≡target sum? No, then skip it.*/
primesTfound= primesTfound + 1 /*bump the number of target primes. */
if cols==0<1 then iterate then iterate /*Build the list (to be shown later)? */
c= commas(y@.j) /*maybe add commas to the number. */
$= $ right(c, max(w, length(c) ) ) /*add a prime ──► list, allow big #'s.*/
if primesTfound//cols\==0 then iterate then iterate /*have we populated a line of output? */
say center(idx, 7)'│' substr($, 2); $= $= /*display what we have so far (cols). */
idx= idx + cols /*bump the index count for the output*/
end /*j*/
 
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/
if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─')
say
say 'Found ' commas(primesTfound) @primes commas(target)title
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Line 1,576 ⟶ 2,015:
@.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13 /*define some low primes. */
!.2=1; !.3=1; !.5=1; !.7=1; !.11=1; @.13=1 /* " " " primes' semaphores. */
#= 6; ssq.#= @.# ** 2 /*number of primes so far; prime². */
/* [↓] generate more primes ≤ high.*/
do j=@.#+2 by 2 to hi /*find odd primes from here on. */
parse var j '' -1 _; if _==5 then iterate /*Jobtain divisiblethe bylast decimal 5?digit (rightof J. dig)*/
if _==5 then iterate; if j// 3==0 then iterate /*"J ÷ by 5? " J ÷ "by 3? */
if j//7==0 then iterate; if j// 711==0 then iterate /*" " " 7? " " " 11? */
do k=6 while sq.k<=j if j//11==0 then iterate /*" " " 11? [↓] divide by the known odd primes.*/
do k=6 while s.k<=j /* [↓] divide by the known odd primes.*/
if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */
end /*k*/ /* [↑] only process numbers ≤ √ J */
#= #+1; @.#= j; ssq.#= j*j; !.j= 1 /*bump # of Ps; assign next P; P²; P# */
end /*j*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
sumDigs: parse arg x 1 s 2 '' -1 z; L= length(x); if L==1 then return s; s= s + z
do m=2 for L-2; s= s + substr(x, m, 1); end; return s</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,597 ⟶ 2,035:
1 │ 997 1,699 1,789 1,879 1,987 2,689 2,797 2,887 3,499 3,697
11 │ 3,769 3,877 3,967 4,597 4,759 4,957 4,993
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────
 
Found 17 primes that are < 5,000 and whose decimal digits sum to 25
Line 1,607 ⟶ 2,046:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 1,674 ⟶ 2,113:
return 1
ok
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,689 ⟶ 2,128:
done...
</pre>
 
=={{header|RPL}}==
<code>∑DIGITS</code> is defined at [[Sum digits of an integer#RPL|Sum digits of an integer]]
≪ { } 799 <span style="color:grey">@ 799 is the smallest integer whose digits sum equals 25, and is not prime : 799 = 47 * 17</span>
'''DO'''
NEXTPRIME
IF DUP <span style="color:blue">∑DIGITS</span> 25 == '''THEN''' SWAP OVER + SWAP '''END'''
'''UNTIL''' DUP 5000 > '''END'''
DROP
≫ '<span style="color:blue">TASK</span>' STO
{{out}}
<pre>
1: {997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993}
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">require 'prime'
 
def digitSum(n)
sum = 0
while n > 0
sum += n % 10
n /= 10
end
return sum
end
 
for p in Prime.take_while { |p| p < 5000 }
if digitSum(p) == 25 then
print p, " "
end
end</syntaxhighlight>
{{out}}
<pre>997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993 </pre>
 
=={{header|Sidef}}==
Simple solution:
<syntaxhighlight lang="ruby">5000.primes.grep { .sumdigits == 25 }.say</syntaxhighlight>
 
Generate such primes from digits (asymptotically faster):
<syntaxhighlight lang="ruby">func generate_from_prefix(limit, digitsum, p, base, digits, t=p) {
 
var seq = [p]
 
digits.each {|d|
var num = (p*base + d)
num <= limit || return seq
 
var sum = (t + d)
sum <= digitsum || return seq
 
seq << __FUNC__(limit, digitsum, num, base, digits, sum)\
.grep { .is_prime }...
}
 
return seq
}
 
func primes_with_digit_sum(limit, digitsum = 25, base = 10, digits = @(^base)) {
digits.grep { _ > 0 }\
.map { generate_from_prefix(limit, digitsum, _, base, digits)... }\
.grep { .sumdigits(base) == digitsum }\
.sort
}
 
say primes_with_digit_sum(5000)</syntaxhighlight>
{{out}}
<pre>
[997, 1699, 1789, 1879, 1987, 2689, 2797, 2887, 3499, 3697, 3769, 3877, 3967, 4597, 4759, 4957, 4993]
</pre>
 
=={{header|Tcl}}==
{{tcllib|math::numtheory}}
Could be made prettier with the staple helper proc lfilter.
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require math::numtheory
namespace path ::tcl::mathop
 
puts [lmap x [math::numtheory::primesLowerThan 5000] {
if {[+ {*}[split $x {}]] == 25} {set x} else continue
}]</syntaxhighlight>
 
{{out}}
<pre>997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993</pre>
 
=={{header|Wren}}==
===Basic===
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./math" for Int
{{libheader|Wren-seq}}
import "./fmt" for Fmt
Although do-able, the stretch goal would take too long in Wren so I haven't bothered.
<lang ecmascript>import "/math" for Int
import "/fmt" for Fmt
import "/seq" for Lst
 
var sumDigits = Fn.new { |n|
Line 1,714 ⟶ 2,235:
}
System.print("The %(primes25.count) primes under 5,000 whose digits sum to 25 are:")
Fmt.tprint("$,6d", primes25, 6)</syntaxhighlight>
for (chunk in Lst.chunks(primes25, 6)) Fmt.print("$,6d", chunk)</lang>
 
{{out}}
Line 1,723 ⟶ 2,244:
3,967 4,597 4,759 4,957 4,993
</pre>
===Stretch===
{{trans|Go}}
{{libheader|Wren-gmp}}
Run time is about 25.5 seconds.
<syntaxhighlight lang="wren">import "./gmp" for Mpz
import "./fmt" for Fmt
 
var z = Mpz.new()
 
var countAll // recursive
countAll = Fn.new { |p, rem, res|
if (rem == 0) {
var b = p[-1]
if ("1379".contains(b)) {
if (z.setStr(p).probPrime(15) > 0) res = res + 1
}
} else {
for (i in 1..rem.min(9)) {
res = countAll.call(p + i.toString, rem - i, res)
}
}
return res
}
 
var n = countAll.call("", 25, 0)
Fmt.print("There are $,d primes whose digits sum to 25 and include no zeros.", n)</syntaxhighlight>
 
{{out}}
<pre>
There are 1,525,141 primes whose digits sum to 25 and include no zeros.
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
 
func SumDigits(N); \Return sum of digits in N
int N, Sum;
[Sum:= 0;
repeat N:= N/10;
Sum:= Sum + rem(0);
until N=0;
return Sum;
];
 
int Cnt, N;
[Cnt:= 0;
for N:= 2 to 5000-1 do
if IsPrime(N) & SumDigits(N) = 25 then
[IntOut(0, N);
Cnt:= Cnt+1;
if rem(Cnt/5) then ChOut(0, 9\tab\) else CrLf(0);
];
CrLf(0);
IntOut(0, Cnt);
Text(0, " primes whose sum of digits is 25.
");
]</syntaxhighlight>
 
{{out}}
<pre>
997 1699 1789 1879 1987
2689 2797 2887 3499 3697
3769 3877 3967 4597 4759
4957 4993
17 primes whose sum of digits is 25.
</pre>
 
=={{header|Zig}}==
{{trans|Nim}}
<syntaxhighlight lang="zig">const std = @import("std");</syntaxhighlight>
<syntaxhighlight lang="zig">fn isPrime(n: u64) bool {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
var d: u64 = 5;
while (d * d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return false;
d += 4;
}
return true;
}</syntaxhighlight>
<syntaxhighlight lang="zig">fn digitSum(n_: u64) u16 {
var n = n_; // parameters are immutable, copy to var
var sum: u16 = 0;
while (n != 0) {
sum += @truncate(u16, n % 10);
n /= 10;
}
return sum;
}</syntaxhighlight>
<syntaxhighlight lang="zig">pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
 
var result = std.ArrayList(u64).init(arena.allocator());
defer result.deinit();
 
{
var n: u64 = 3;
while (n <= 5000) : (n += 2)
if (digitSum(n) == 25 and isPrime(n))
try result.append(n);
}
 
const stdout = std.io.getStdOut().writer();
for (result.items, 0..) |n, i|
_ = try stdout.print("{d:4}{s}", .{ n, if ((i + 1) % 6 == 0) "\n" else " " });
}</syntaxhighlight>
{{out}}
<pre> 997 1699 1789 1879 1987 2689
2797 2887 3499 3697 3769 3877
3967 4597 4759 4957 4993</pre>
9,476

edits