Primes which contain only one odd digit
- Task
Show on this page those primes under 1,000 which when expressed in decimal contain only one odd digit.
- Stretch goal
Show on this page only the count of those primes under 1,000,000 which when expressed in decimal contain only one odd digit.
11l
F is_prime(n)
I n == 2
R 1B
I n < 2 | n % 2 == 0
R 0B
L(i) (3 .. Int(sqrt(n))).step(2)
I n % i == 0
R 0B
R 1B
F hasLastDigitOdd(=n)
n I/= 10
L n != 0
I ((n % 10) [&] 1) != 0
R 0B
n I/= 10
R 1B
V l = (1.<1000).step(2).filter(n -> hasLastDigitOdd(n) & is_prime(n))
print(‘Found ’l.len‘ primes with only one odd digit below 1000:’)
L(n) l
print(‘#3’.format(n), end' I (L.index + 1) % 9 == 0 {"\n"} E ‘ ’)
V count = 0
L(n) (1.<1'000'000).step(2)
I hasLastDigitOdd(n) & is_prime(n)
count++
print("\nFound "count‘ primes with only one odd digit below 1000000.’)
- Output:
Found 45 primes with only one odd digit below 1000: 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Found 2560 primes with only one odd digit below 1000000.
Action!
INCLUDE "H6:SIEVE.ACT"
BYTE FUNC OddDigitsCount(INT x)
BYTE c,d
c=0
WHILE x#0
DO
d=x MOD 10
IF (d&1)=1 THEN
c==+1
FI
x==/10
OD
RETURN (c)
PROC Main()
DEFINE MAX="999"
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 OddDigitsCount(i)=1 THEN
PrintI(i) Put(32)
count==+1
FI
OD
PrintF("%E%EThere are %I primes",count)
RETURN
- Output:
Screenshot from Atari 8-bit computer
3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 There are 45 primes
ALGOL 68
BEGIN # find primes whose decimal representation contains only one odd digit #
# sieve the primes to 1 000 000 #
PR read "primes.incl.a68" PR
[]BOOL prime = PRIMESIEVE 1 000 000;
# show a count of primes #
PROC show total = ( INT count, INT limit, STRING name )VOID:
print( ( newline, "Found ", whole( count, 0 ), " ", name, " primes upto ", whole( limit, 0 ), newline ) );
# find the appropriate primes #
# 2 is the only even prime, so the final digit must be odd for primes > 2 #
# so we only need to check that the digits other than the last are all even #
INT show max = 1 000;
INT p1odd count := 0;
FOR n FROM 3 TO UPB prime DO
IF prime[ n ] THEN
BOOL p1odd := TRUE;
INT v := n OVER 10;
WHILE v > 0 AND ( p1odd := NOT ODD v ) DO
v OVERAB 10
OD;
IF p1odd THEN
# the prime has only 1 odd digit #
p1odd count +:= 1;
IF n <= show max THEN
print( ( whole( n, -5 ) ) );
IF p1odd count MOD 12 = 0 THEN print( ( newline ) ) FI
FI
FI
FI;
IF n = show max THEN
print( ( newline ) );
show total( p1odd count, show max, "single-odd-digit" )
FI
OD;
show total( p1odd count, UPB prime, "single-odd-digit" )
END
- Output:
3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Found 45 single-odd-digit primes upto 1000 Found 2560 single-odd-digit primes upto 1000000
Arturo
onlyOneOddDigit?: function [n][
and? -> prime? n
-> one? select digits n => odd?
]
primesWithOnlyOneOddDigit: select 1..1000 => onlyOneOddDigit?
loop split.every: 9 primesWithOnlyOneOddDigit 'x ->
print map x 's -> pad to :string s 4
nofPrimesBelow1M: enumerate 1..1000000 => onlyOneOddDigit?
print ""
print ["Found" nofPrimesBelow1M "primes with only one odd digit below 1000000."]
- Output:
3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Found 2560 primes with only one odd digit below 1000000.
AWK
# syntax: GAWK -f PRIMES_WHICH_CONTAIN_ONLY_ONE_ODD_NUMBER.AWK
BEGIN {
start = 1
stop = 999
for (i=start; i<=stop; i++) {
if (is_prime(i)) {
if (gsub(/[13579]/,"&",i) == 1) {
rec_odd = sprintf("%s%5d%1s",rec_odd,i,++count_odd%10?"":"\n")
}
if (gsub(/[02468]/,"&",i) == 1) {
rec_even = sprintf("%s%5d%1s",rec_even,i,++count_even%10?"":"\n")
}
}
}
printf("%s\nPrimes which contain only one odd number %d-%d: %d\n\n",rec_odd,start,stop,count_odd)
printf("%s\nPrimes which contain only one even number %d-%d: %d\n\n",rec_even,start,stop,count_even)
exit(0)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
- Output:
3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Primes which contain only one odd number 1-999: 45 2 23 29 41 43 47 61 67 83 89 101 103 107 109 127 149 163 167 181 211 233 239 251 257 271 277 293 307 347 349 367 383 389 419 431 433 439 457 479 491 499 503 509 521 523 541 547 563 569 587 613 617 619 631 653 659 673 677 691 701 709 727 743 761 769 787 811 839 853 857 859 877 907 929 941 947 967 983 Primes which contain only one even number 1-999: 78
C#
Modifies a conventional prime sieve to cull the items with more than one odd digit.
using System;
using System.Collections.Generic;
class Program
{
// starts as an ordinary odds-only prime sieve, but becomes
// extraordinary after the else statement...
static List<uint> sieve(uint max, bool ordinary = false)
{
uint k = ((max - 3) >> 1) + 1,
lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1;
var pl = new List<uint> { };
var ic = new bool[k];
for (uint i = 0, p = 3; i < lmt; i++, p += 2) if (!ic[i])
for (uint j = (p * p - 3) >> 1; j < k; j += p) ic[j] = true;
if (ordinary)
{
pl.Add(2);
for (uint i = 0, j = 3; i < k; i++, j += 2)
if (!ic[i]) pl.Add(j);
}
else
for (uint i = 0, j = 3, t = j; i < k; i++, t = j += 2)
if (!ic[i])
{
while ((t /= 10) > 0)
if (((t % 10) & 1) == 1) goto skip;
pl.Add(j);
skip:;
}
return pl;
}
static void Main(string[] args)
{
var pl = sieve((uint)1e9);
uint c = 0, l = 10, p = 1;
Console.WriteLine("List of one-odd-digit primes < 1,000:");
for (int i = 0; pl[i] < 1000; i++)
Console.Write("{0,3}{1}", pl[i], i % 9 == 8 ? "\n" : " ");
string fmt = "\nFound {0:n0} one-odd-digit primes < 10^{1} ({2:n0})";
foreach (var itm in pl)
if (itm < l) c++;
else Console.Write(fmt, c++, p++, l, l *= 10);
Console.Write(fmt, c++, p++, l);
}
}
- Output:
List of one-odd-digit primes < 1,000: 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Found 3 one-odd-digit primes < 10^1 (10) Found 12 one-odd-digit primes < 10^2 (100) Found 45 one-odd-digit primes < 10^3 (1,000) Found 171 one-odd-digit primes < 10^4 (10,000) Found 619 one-odd-digit primes < 10^5 (100,000) Found 2,560 one-odd-digit primes < 10^6 (1,000,000) Found 10,774 one-odd-digit primes < 10^7 (10,000,000) Found 46,708 one-odd-digit primes < 10^8 (100,000,000) Found 202,635 one-odd-digit primes < 10^9 (1,000,000,000)
C++
#include <vector>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <iterator>
bool isPrime( int n ) {
int limit = static_cast<int>( std::floor( std::sqrt( static_cast<double>( n ) ) ) ) ;
for ( int i = 2 ; i < limit + 1 ; i++ ) {
if ( n % i == 0 ) {
return false ;
}
}
return true ;
}
bool hasOneOdd( int n ) {
std::vector<int> digits ;
while ( n != 0 ) {
digits.push_back( n % 10 ) ;
n /= 10 ;
}
return std::count_if( digits.begin( ) , digits.end( ) , []( int i ) { return
i % 2 == 1 ; } ) == 1 ;
}
bool condition( int n ) {
return isPrime( n ) && hasOneOdd( n ) ;
}
int main( ) {
std::vector<int> primes ;
for ( int i = 2 ; i < 1000 ; i++ ) {
if ( condition( i ) )
primes.push_back( i ) ;
}
std::cout << "Primes under 1000 with only one odd digit :\n" ;
std::copy( primes.begin( ) , primes.end( ) , std::ostream_iterator<int>( std::cout ,
" " ) ) ;
for ( int i = 1000 ; i < 1000000 ; i++ ) {
if ( condition( i ) )
primes.push_back( i ) ;
}
std::cout << "\nThe number of primes under 1000000 with only one odd digit is " <<
primes.size( ) << " !\n " ;
return 0 ;
}
- Output:
Primes under 1000 with only one odd digit : 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 The number of primes under 1000000 with only one odd digit is 2560 !
Delphi
function IsPrime(N: int64): boolean;
{Fast, optimised prime test}
var I,Stop: int64;
begin
if (N = 2) or (N=3) then Result:=true
else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false
else
begin
I:=5;
Stop:=Trunc(sqrt(N+0.0));
Result:=False;
while I<=Stop do
begin
if ((N mod I) = 0) or ((N mod (I + 2)) = 0) then exit;
Inc(I,6);
end;
Result:=True;
end;
end;
procedure GetDigits(N: integer; var IA: TIntegerDynArray);
{Get an array of the integers in a number}
var T: integer;
begin
SetLength(IA,0);
repeat
begin
T:=N mod 10;
N:=N div 10;
SetLength(IA,Length(IA)+1);
IA[High(IA)]:=T;
end
until N<1;
end;
procedure ShowOneOddDigitPrime(Memo: TMemo);
var I,Cnt1,Cnt2: integer;
var IA: TIntegerDynArray;
var S: string;
function HasOneOddDigit(N: integer): boolean;
var I,Odd: integer;
begin
Odd:=0;
GetDigits(N,IA);
for I:=0 to High(IA) do
if (IA[I] and 1)=1 then Inc(Odd);
Result:=Odd=1;
end;
begin
Cnt1:=0; Cnt2:=0;
S:='';
for I:=0 to 1000000-1 do
if IsPrime(I) then
if HasOneOddDigit(I) then
begin
Inc(Cnt1);
if I<1000 then
begin
Inc(Cnt2);
S:=S+Format('%4D',[I]);
If (Cnt2 mod 5)=0 then S:=S+CRLF;
end;
end;
Memo.Lines.Add(S);
Memo.Lines.Add('Count < 1,000 = '+IntToStr(Cnt2));
Memo.Lines.Add('Count < 1,000,000 = '+IntToStr(Cnt1));
end;
- Output:
3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Count < 1,000 = 45 Count < 1,000,000 = 2560 Elapsed Time: 171.630 ms.
EasyLang
fastfunc isprim num .
i = 2
while i <= sqrt num
if num mod i = 0
return 0
.
i += 1
.
return 1
.
fastfunc nextprim prim .
repeat
prim += 1
until isprim prim = 1
.
return prim
.
func digodd n .
while n > 0
r += if n mod 2 = 1
n = n div 10
.
return r
.
p = 2
repeat
if digodd p = 1
write p & " "
.
p = nextprim p
until p >= 1000
.
- Output:
3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887
F#
This task uses Extensible Prime Generator (F#)
// Primes which contain only one odd number. Nigel Galloway: July 28th., 2021
let rec fN g=function 2->false |n when g=0->n=1 |n->fN (g/10) (n+g%2)
primes32()|>Seq.takeWhile((>)1000)|>Seq.filter(fun g->fN g 0)|>Seq.iter(printf "%d "); printfn ""
- Output:
3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887
Factor
USING: grouping io lists lists.lazy literals math math.primes
numspec prettyprint ;
<<
DIGIT: o 357
DIGIT: q 1379
DIGIT: e 2468
DIGIT: E 02468
NUMSPEC: one-odd-candidates o eq eEq ... ;
>>
CONSTANT: p $[ one-odd-candidates [ prime? ] lfilter ]
"Primes with one odd digit under 1,000:" print
p [ 1000 < ] lwhile list>array 9 group simple-table.
"\nCount of such primes under 1,000,000:" print
p [ 1,000,000 < ] lwhile llength .
"\nCount of such primes under 1,000,000,000:" print
p [ 1,000,000,000 < ] lwhile llength .
- Output:
Primes with one odd digit under 1,000: 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Count of such primes under 1,000,000: 2560 Count of such primes under 1,000,000,000: 202635
FreeBASIC
#include "isprime.bas"
function b(j as uinteger, n as uinteger) as uinteger
'auxiliary function for evendig below
dim as uinteger m = int(log(n-1)/log(5))
return int((n-1-5^m)/5^j)
end function
function evendig(n as uinteger) as uinteger
'produces the integers with only even digits
dim as uinteger m = int(log(n-1)/log(5)), a
a = ((2*b(m, n)) mod 8 + 2)*10^m
if n<=1 or m=0 then return a
for j as uinteger = 0 to m-1
a += ((2*b(j, n)) mod 10)*10^j
next j
return a
end function
dim as uinteger n=1, count = 0, p=1
while p<1000000
p = 1 + evendig(n) 'if it's a prime the odd digit must be the last one
if isprime(p) then
count += 1
if p<1000 then print p
end if
n+=1
wend
print "There are ";count;" such primes below one million."
Go
package main
import (
"fmt"
"rcu"
)
func allButOneEven(prime int) bool {
digits := rcu.Digits(prime, 10)
digits = digits[:len(digits)-1]
allEven := true
for _, d := range digits {
if d&1 == 1 {
allEven = false
break
}
}
return allEven
}
func main() {
const (
LIMIT = 999
LIMIT2 = 9999999999
MAX_DIGITS = 3
)
primes := rcu.Primes(LIMIT)
var results []int
for _, prime := range primes[1:] {
if allButOneEven(prime) {
results = append(results, prime)
}
}
fmt.Println("Primes under", rcu.Commatize(LIMIT+1), "which contain only one odd digit:")
for i, p := range results {
fmt.Printf("%*s ", MAX_DIGITS, rcu.Commatize(p))
if (i+1)%9 == 0 {
fmt.Println()
}
}
fmt.Println("\nFound", len(results), "such primes.\n")
primes = rcu.Primes(LIMIT2)
count := 0
pow := 10
for _, prime := range primes[1:] {
if allButOneEven(prime) {
count++
}
if prime > pow {
fmt.Printf("There are %7s such primes under %s\n", rcu.Commatize(count), rcu.Commatize(pow))
pow *= 10
}
}
fmt.Printf("There are %7s such primes under %s\n", rcu.Commatize(count), rcu.Commatize(pow))
}
- Output:
Primes under 1,000 which contain only one odd digit: 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Found 45 such primes. There are 3 such primes under 10 There are 12 such primes under 100 There are 45 such primes under 1,000 There are 171 such primes under 10,000 There are 619 such primes under 100,000 There are 2,560 such primes under 1,000,000 There are 10,774 such primes under 10,000,000 There are 46,708 such primes under 100,000,000 There are 202,635 such primes under 1,000,000,000 There are 904,603 such primes under 10,000,000,000
Haskell
import Data.List (intercalate, maximum, transpose)
import Data.List.Split (chunksOf)
import Data.Numbers.Primes (primes)
import Text.Printf (printf)
------------------ ONE ODD DECIMAL DIGIT -----------------
oneOddDecimalDigit :: Int -> Bool
oneOddDecimalDigit =
(1 ==) . length . filter odd . digits
digits :: Int -> [Int]
digits = fmap (read . return) . show
--------------------------- TEST -------------------------
main :: IO ()
main = do
putStrLn "Below 1000:"
(putStrLn . table " " . chunksOf 10 . fmap show) $
sampleBelow 1000
putStrLn "Count of matches below 10E6:"
(print . length) $
sampleBelow 1000000
sampleBelow :: Int -> [Int]
sampleBelow =
filter oneOddDecimalDigit
. flip takeWhile primes
. (>)
------------------------- DISPLAY ------------------------
table :: String -> [[String]] -> String
table gap rows =
let ws = maximum . fmap length <$> transpose rows
pw = printf . flip intercalate ["%", "s"] . show
in unlines $ intercalate gap . zipWith pw ws <$> rows
- Output:
Below 1000: 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Count of matches below 10E6: 2560
J
getOneOdds=. #~ 1 = (2 +/@:| "."0@":)"0
primesTo=. i.&.(p:inv)
_15 ]\ getOneOdds primesTo 1000
3 5 7 23 29 41 43 47 61 67 83 89 223 227 229
241 263 269 281 283 401 409 421 443 449 461 463 467 487 601
607 641 643 647 661 683 809 821 823 827 829 863 881 883 887
# getOneOdds primesTo 1e6
2560
jq
Works with gojq, the Go implementation of jq
As noted in the Julia entry, if only one digit of a prime is odd, then that digit is in the ones place. The first solution presented here uses this observation to generate plausible candidates. The second solution is more brutish and slower but simpler.
See e.g. Erdős-primes#jq for a suitable implementation of `is_prime`.
Fast solution
### Preliminaries
def count(s): reduce s as $x (null; .+1);
def emit_until(cond; stream):
label $out | stream | if cond then break $out else . end;
# Output: an unbounded stream
def primes_with_exactly_one_odd_digit:
# Output: a stream of candidate strings, in ascending numerical order
def candidates:
# input is $width
def evens:
. as $width
| if $width == 0 then ""
else ("0","2","4","6","8") as $i
| ((.-1)|evens) as $j
| "\($i)\($j)"
end;
("2","4","6","8") as $leading
| evens as $even
| ("1","3","5","7","9") as $odd
| "\($leading)\($even)\($odd)";
(3,5,7),
(range(0; infinite)
| candidates | tonumber
| select(is_prime)) ;
### The Task
emit_until(. > 1000; primes_with_exactly_one_odd_digit),
"\nThe number of primes less than 1000000 with exactly one odd digits is \(count(emit_until(. > 1000000; primes_with_exactly_one_odd_digit)))."
- Output:
3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 The number of primes less than 1000000 with exactly one odd digits is 2560.
A simpler but slower solution
# Input is assumed to be prime.
# So we only need check the other digits are all even.
def prime_has_exactly_one_odd_digit:
if . == 2 then false
# The codepoints for the odd digits are also odd: [49,51,53,55,57]
else all(tostring | explode[:-1][]; . % 2 == 0)
end;
def primes_with_exactly_one_odd_digit_crudely:
# It is much faster to check for primality afterwards.
range(3; infinite; 2)
| select(prime_has_exactly_one_odd_digit and is_prime);
Julia
If only one digit of a prime is odd, then that odd digit is the ones place digit. We don't actually need to check for an odd first digit once we exclude 2.
using Primes
function isoneoddprime(n, base = 10)
d = digits(n ÷ base, base = base)
return n != 2 && all(iseven, d)
end
found = filter(isoneoddprime, primes(1000))
println("Found $(length(found)) primes with one odd digit in base 10:")
foreach(p -> print(rpad(last(p), 5), first(p) % 9 == 0 ? "\n" : ""), enumerate(found))
println("\nThere are ", count(isoneoddprime, primes(1_000_000)),
" primes with only one odd digit in base 10 between 1 and 1,000,000.")
- Output:
Found 45 primes with one odd digit in base 10: 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 There are 2560 primes with only one odd digit in base 10 between 1 and 1,000,000.
Mathematica / Wolfram Language
Labeled[Cases[
NestWhileList[NextPrime,
2, # <
1000 &], _?(Total[Mod[IntegerDigits@#, 2]] ==
1 &)], "Primes < 1000 with one odd digit", Top]
Labeled[Length@
Cases[NestWhileList[NextPrime,
2, # <
1000000 &], _?(Total[Mod[IntegerDigits@#, 2]] ==
1 &)], "Number of primes < 1,000,000 with one odd digit", Top]
- Output:
Primes < 1000 with one odd digit {3,5,7,23,29,41,43,47,61,67,83,89,223,227,229,241,263,269,281,283,401,409,421,443,449,461,463,467,487,601,607,641,643,647,661,683,809,821,823,827,829,863,881,883,887}
Number of primes < 1,000,000 with one odd digit 2560
Nim
import sequtils, strutils
func isPrime(n: Positive): bool =
if n == 1: return false
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 hasLastDigitOdd(n: Natural): bool =
var n = n
n = n div 10
while n != 0:
if (n mod 10 and 1) != 0: return false
n = n div 10
result = true
iterator primesOneOdd(lim: Positive): int =
var n = 1
while n <= lim:
if n.hasLastDigitOdd and n.isPrime:
yield n
inc n, 2
let list = toSeq(primesOneOdd(1000))
echo "Found $# primes with only one odd digit below 1000:".format(list.len)
for i, n in list:
stdout.write ($n).align(3), if (i + 1) mod 9 == 0: '\n' else: ' '
var count = 0
for _ in primesOneOdd(1_000_000):
inc count
echo "\nFound $# primes with only one odd digit below 1_000_000.".format(count)
- Output:
Found 45 primes with only one odd digit below 1000: 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Found 2560 primes with only one odd digit below 1_000_000.
Perl
#!/usr/bin/perl
use strict;
use warnings;
use ntheory qw( primes );
my @singleodd = grep tr/13579// == 1, @{ primes(1e3) };
my $million = grep tr/13579// == 1, @{ primes(1e6) };
print "found " . @singleodd .
"\n\n@singleodd\n\nfound $million in 1000000\n" =~ s/.{60}\K /\n/gr;
- Output:
found 45 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 found 2560 in 1000000
Phix
Relies on the fact that '0', '1', '2', etc are just as odd/even as 0, 1, 2, etc.
with javascript_semantics function oneodddigit(integer n) return sum(apply(sprint(n),odd))=1 end function sequence res = filter(get_primes_le(1_000),oneodddigit) printf(1,"Found %d one odd digit primes < 1,000: %V\n",{length(res),shorten(res,"",5)})
- Output:
Found 45 one odd digit primes < 1,000: {3,5,7,23,29,"...",829,863,881,883,887}
stretch
Fast skip from 11 direct to 20+, from 101 direct to 200+, etc. Around forty times faster than the above would be, but less than twice as fast as it would be without such skipping.
Of course the last digit must/will be odd for all primes (other than 2 which has no odd digit anyway), and all digits prior to that must be even, eg 223 or 241, and not 257 or 743.
with javascript_semantics for m=1 to iff(platform()=JS?8:9) do integer m10 = power(10,m) sequence primes = get_primes_le(m10) integer n = 2, count = 0 while n<=length(primes) do integer p = primes[n], skip = 10 while true do p = floor(p/10) if odd(p) then p = (p+1)*skip n = abs(binary_search(p,primes)) exit end if if p=0 then count += 1 n += 1 exit end if skip *=10 end while end while printf(1,"Found %,d one odd digit primes < %,d\n",{count,m10}) end for
- Output:
Found 3 one odd digit primes < 10 Found 12 one odd digit primes < 100 Found 45 one odd digit primes < 1,000 Found 171 one odd digit primes < 10,000 Found 619 one odd digit primes < 100,000 Found 2,560 one odd digit primes < 1,000,000 Found 10,774 one odd digit primes < 10,000,000 Found 46,708 one odd digit primes < 100,000,000 Found 202,635 one odd digit primes < 1,000,000,000
Python
def prime(n):
if n == 1:
return False
if n == 2:
p.append(n)
return True
for y in p:
if n % y == 0:
return False
if y > int(n ** 0.5):
p.append(n)
return True
p = []
x = 1
stopper = 0
lis = []
for i in range(0, 1000000):
x += 1
if prime(x) == True:
str_x = str(x)
if str(x).count("1") + str(x).count("3") + str(x).count("5") + str(x).count("7") + str(x).count("9") == 1:
lis.append(x)
if int(x) == 1000 and stopper == 0:
print(f'There are {len(lis)} primes with one odd digit less than 1000')
for i in lis:
print(i)
print(f'There are {len(lis)} primes with one odd digit less than 1000000')
- Output:
There are 45 primes with one odd digit less than 1000 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 ... 881 883 887 There are 2560 primes with one odd digit less than 1000000
Quackery
isprime
is defined at Primality by trial division#Quackery.
evendigits
returns the nth number which has only even digits and ends with zero. There are self-evidently 5^5 of them less than 1000000.
We know that the only prime ending with a 5 is 5. So we can omit generating candidate numbers that end with a 5, and stuff the 5 into the right place in the nest (i.e. as item #1; item #0 will be 3) afterwards. This explains the lines ' [ 1 3 7 9 ] witheach
and 5 swap 1 stuff
.
[ [] swap
[ 5 /mod
rot join swap
dup 0 = until ]
drop
0 swap witheach
[ swap 10 * + ]
20 * ] is evendigits ( n --> n )
[]
5 5 ** times
[ i^ evendigits
' [ 1 3 7 9 ] witheach
[ over +
dup isprime iff
[ swap dip join ]
else drop ]
drop ]
5 swap 1 stuff
dup say "Qualifying primes < 1000:"
dup findwith [ 999 > ] [ ]
split drop unbuild
1 split nip -1 split drop
nest$ 44 wrap$ cr cr
say "Number of qualifying primes < 1000000: "
size echo
- Output:
Qualifying primes < 1000: 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Number of qualifying primes < 1000000: 2560
Raku
put display ^1000 .grep: { ($_ % 2) && .is-prime && (.comb[^(*-1)].all %% 2) }
sub display ($list, :$cols = 10, :$fmt = '%6d', :$title = "{+$list} matching:\n" ) {
cache $list;
$title ~ $list.batch($cols)».fmt($fmt).join: "\n"
}
- Output:
45 matching: 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887
REXX
/*REXX pgm finds & displays primes (base ten) that contain only one odd digit (< 1,000).*/
parse arg hi cols . /*obtain optional argument from the CL.*/
if hi=='' | hi=="," then hi= 1000 /*Not specified? Then use the default.*/
if cols=='' | cols=="," then cols= 10 /* " " " " " " */
call genP /*build array of semaphores for primes.*/
w= 10 /*width of a number in any column. */
title= ' primes N (in base ten) that only contain one odd digit, where N <' commas(hi)
if cols>0 then say ' index │'center(title, 1 + cols*(w+1) )
if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─')
found= 0; idx= 1 /*initialize # of primes found; IDX. */
$= /*list of primes that contain a string.*/
do j=2 for #-1; p= @.j; L= length(p) /*find primes with leading/trailing dig*/
z= 0
do k=L by -1 for L
if verify(substr(p, k, 1), 13579, 'M')>0 then do; z= z+1; if z>1 then iterate j /* ◄■■■■■■■ the filter.*/
end
end /*k*/
found= found + 1 /*bump the number of primes found. */
if cols<=0 then iterate /*Build the list (to be shown later)? */
c= commas(@.j) /*maybe add commas to the number. */
$= $ right(c, max(w, length(c) ) ) /*add a prime ──► $ list, allow big #*/
if found//cols\==0 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(found) title
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */
#=5; sq.#= @.# **2 /*number of primes so far; prime square*/
do j=@.#+2 by 2 to hi-1 /*find odd primes from here on. */
parse var j '' -1 _; if _==5 then iterate /*J divisible by 5? (right dig)*/
if j// 3==0 then iterate /*" " " 3? */
if j// 7==0 then iterate /*" " " 7? */
do k=5 while sq.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; sq.#= j*j /*bump # of Ps; assign next P; P square*/
end /*j*/; return
- output when using the default inputs:
index │ primes N (in base ten) that only contain one odd digit, where N < 1,000 ───────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────── 1 │ 3 5 7 23 29 41 43 47 61 67 11 │ 83 89 223 227 229 241 263 269 281 283 21 │ 401 409 421 443 449 461 463 467 487 601 31 │ 607 641 643 647 661 683 809 821 823 827 41 │ 829 863 881 883 887 ───────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────── Found 45 primes N (in base ten) that only contain one odd digit, where N < 1,000
- output when using the inputs of: 1000000 -1
Found 2,560 primes N (in base ten) that only contain one odd digit, where N < 1,000,000
Ring
load "stdlib.ring"
see "working..." + nl
see "Primes which contain only one odd number:" + nl
row = 0
for n = 1 to 1000
odd = 0
str = string(n)
for m = 1 to len(str)
if number(str[m])%2 = 1
odd++
ok
next
if odd = 1 and isprime(n)
see "" + n + " "
row++
if row%5 = 0
see nl
ok
ok
next
see "Found " + row + " prime numbers" + nl
see "done..." + nl
- Output:
working... Primes which contain only one odd number: 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Found 45 prime numbers done...
RPL
≪ →STR 0 1 3 PICK SIZE FOR j OVER j DUP SUB NUM 2 MOD + NEXT NIP ≫ ≫ 'ODDCNT' STO ≪ { } 1 DO NEXTPRIME IF DUP ODDCNT 1 == THEN SWAP OVER + SWAP END UNTIL DUP 1000 ≥ END DROP ≫ ≫ 'TASK' STO
- Output:
1: {3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887}
Ruby
require 'prime'
def single_odd?(pr)
d = pr.digits
d.first.odd? && d[1..].all?(&:even?)
end
res = Prime.each(1000).select {|pr| single_odd?(pr)}
res.each_slice(10){|s| puts "%4d"*s.size % s}
n = 1_000_000
count = Prime.each(n).count{|pr| single_odd?(pr)}
puts "\nFound #{count} single-odd-digit primes upto #{n}."
- Output:
3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Found 2560 single-odd-digit primes upto 1000000.
Rust
fn is_prime( number : u32 ) -> bool {
let limit : u32 = (number as f32).sqrt( ).floor( ) as u32 ;
(2..=limit).all( | i | number % i != 0 )
}
fn has_one_odd( mut number : u32 ) -> bool {
let mut digits : Vec<u32> = Vec::new( ) ;
while number != 0 {
digits.push( number % 10 ) ;
number /= 10 ;
}
digits.into_iter( ).filter( | &d | d % 2 == 1 ).count( ) == 1
}
fn main() {
let mut solution_primes : Vec<u32> = Vec::new( ) ;
(2..1000).filter( | &d | is_prime( d ) && has_one_odd( d )).for_each( | n | {
solution_primes.push( n ) ;
} ) ;
println!("Prime numbers under 1000 with only one odd digit:") ;
println!("{:?}" , solution_primes ) ;
println!("Number of primes under 1000000 with only one odd digit : {}" ,
(2..1000000).filter( | &d | is_prime( d ) && has_one_odd( d ) ).count( ) ) ;
- Output:
[3, 5, 7, 23, 29, 41, 43, 47, 61, 67, 83, 89, 223, 227, 229, 241, 263, 269, 281, 283, 401, 409, 421, 443, 449, 461, 463, 467, 487, 601, 607, 641, 643, 647, 661, 683, 809, 821, 823, 827, 829, 863, 881, 883, 887] Number of primes under 1000000 with only one odd digit : 2560
Sidef
func primes_with_one_odd_digit(upto, base = 10) {
upto = prev_prime(upto+1)
var list = []
var digits = @(^base)
var even_digits = digits.grep { .is_even }
var odd_digits = digits.grep { .is_odd && .is_coprime(base) }
list << digits.grep { .is_odd && .is_prime && !.is_coprime(base) }...
for k in (0 .. upto.ilog(base)) {
even_digits.variations_with_repetition(k, {|*a|
next if (a.last == 0)
var v = a.digits2num(base)
odd_digits.each {|d|
var n = (v*base + d)
list << n if (n.is_prime && (n <= upto))
}
})
}
list.sort
}
with (1e3) {|n|
var list = primes_with_one_odd_digit(n)
say "There are #{list.len} primes under #{n.commify} which contain only one odd digit:"
list.each_slice(9, {|*a| say a.map { '%3s' % _ }.join(' ') })
}
say ''
for k in (1..8) {
var count = primes_with_one_odd_digit(10**k).len
say "There are #{'%6s' % count.commify} such primes <= 10^#{k}"
}
- Output:
There are 45 primes under 1,000 which contain only one odd digit: 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 There are 3 such primes <= 10^1 There are 12 such primes <= 10^2 There are 45 such primes <= 10^3 There are 171 such primes <= 10^4 There are 619 such primes <= 10^5 There are 2,560 such primes <= 10^6 There are 10,774 such primes <= 10^7 There are 46,708 such primes <= 10^8
Wren
import "./math" for Int
import "./fmt" for Fmt
var limit = 999
var maxDigits = 3
var primes = Int.primeSieve(limit)
var results = []
for (prime in primes.skip(1)) {
if (Int.digits(prime)[0...-1].all { |d| d & 1 == 0 }) results.add(prime)
}
Fmt.print("Primes under $,d which contain only one odd digit:", limit + 1)
Fmt.tprint("$,%(maxDigits)d", results, 9)
System.print("\nFound %(results.count) such primes.\n")
limit = 1e9 - 1
primes = Int.primeSieve(limit)
var count = 0
var pow = 10
for (prime in primes.skip(1)) {
if (Int.digits(prime)[0...-1].all { |d| d & 1 == 0 }) count = count + 1
if (prime > pow) {
Fmt.print("There are $,7d such primes under $,d", count, pow)
pow = pow * 10
}
}
Fmt.print("There are $,7d such primes under $,d", count, pow)
- Output:
Primes under 1,000 which contain only one odd digit: 3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 Found 45 such primes. There are 3 such primes under 10 There are 12 such primes under 100 There are 45 such primes under 1,000 There are 171 such primes under 10,000 There are 619 such primes under 100,000 There are 2,560 such primes under 1,000,000 There are 10,774 such primes under 10,000,000 There are 46,708 such primes under 100,000,000 There are 202,635 such primes under 1,000,000,000
XPL0
func IsPrime(N); \Return 'true' if N is a prime number
int N, I;
[if N <= 1 then return false;
for I:= 2 to sqrt(N) do
if rem(N/I) = 0 then return false;
return true;
];
int Count, N, Hun, Ten, One;
[Count:= 0;
for Hun:= 0 to 4 do
for Ten:= 0 to 4 do
for One:= 0 to 4 do
[N:= Hun*200 + Ten*20 + One*2 + 1;
if IsPrime(N) then
[IntOut(0, N);
Count:= Count+1;
if rem(Count/10) = 0 then CrLf(0) else ChOut(0, 9\tab\);
];
];
CrLf(0);
IntOut(0, Count);
Text(0, " such numbers found.
");
]
- Output:
3 5 7 23 29 41 43 47 61 67 83 89 223 227 229 241 263 269 281 283 401 409 421 443 449 461 463 467 487 601 607 641 643 647 661 683 809 821 823 827 829 863 881 883 887 45 such numbers found.
- Draft Programming Tasks
- Prime Numbers
- 11l
- Action!
- Action! Sieve of Eratosthenes
- ALGOL 68
- ALGOL 68-primes
- Arturo
- AWK
- C sharp
- C++
- Delphi
- SysUtils,StdCtrls
- EasyLang
- F Sharp
- Factor
- Factor-numspec
- FreeBASIC
- Go
- Go-rcu
- Haskell
- J
- Jq
- Julia
- Mathematica
- Wolfram Language
- Nim
- Perl
- Phix
- Python
- Quackery
- Raku
- REXX
- Ring
- RPL
- Ruby
- Rust
- Sidef
- Wren
- Wren-math
- Wren-fmt
- XPL0