Primes whose sum of digits is 25
- Task
Show primes which sum of digits is 25
Let 0 < n < 5000
- Stretch goal
Show the total number of all such primes that do not contain any zeroes.
Phix
<lang Phix>function sum25(integer p) return sum(sq_sub(sprint(p),'0'))=25 end function sequence res = filter(get_primes_le(5000),sum25) string r = join(shorten(apply(res,sprint),"",4)) printf(1,"%d sum25 primes less than 5000 found: %s\n",{length(res),r})</lang>
- Output:
17 sum25 primes less than 5000 found: 997 1699 1789 1879 ... 4597 4759 4957 4993
Stretch goal <lang Phix>include mpfr.e atom t0 = time(), t1 = time()+1 mpz pz = mpz_init(0)
function sum25(string p, integer rem, res=0)
if rem=0 then if find(p[$],"1379") then -- (saves 13s) mpz_set_str(pz,p) if mpz_prime(pz) then res += 1 if time()>t1 then progress("%d, %s...",{res,p}) t1 = time()+1 end if end if end if else for i=1 to min(rem,9) do res = sum25(p&'0'+i,rem-i,res) end for end if return res
end function
printf(1,"There are %,d sum25 primes that contain no zeroes\n",sum25("",25)) ?elapsed(time()-t0)</lang>
- Output:
There are 1,525,141 sum25 primes that contain no zeroes "1 minute and 27s"
Ring
<lang ring> load "stdlib.ring"
row = 0 limit1 = 25 limit2 = 5000
for n = 1 to limit2
if isprime(n) bool = sum25(n) if bool = 1 row = row + 1 see "" + n + " " if (row%5) = 0 see nl ok ok ok
next
func sum25(n)
sum = 0 str = string(n) for n = 1 to len(str) sum = sum + number(str[n]) next if sum = limit1 return 1 ok
</lang>
- Output:
997 1699 1789 1879 1987 2689 2797 2887 3499 3697 3769 3877 3967 4597 4759 4957 4993