Unprimeable numbers: Difference between revisions

m
m (→‎{{header|Raku}}: note use of 'ntheory' module)
m (→‎{{header|Wren}}: Minor tidy)
 
(2 intermediate revisions by 2 users not shown)
Line 55:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V limit = 10'000'000
V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
Line 102:
 
L(v) first
print(L.index‘ ending: ’v)</langsyntaxhighlight>
 
{{out}}
Line 127:
If running this with Algol 68G under Windows (and possibly other platforms) you will need to increase the heap size by specifying e.g. <code>-heap 256M</code> on the command line.
{{libheader|ALGOL 68-primes}}
<langsyntaxhighlight lang="algol68">BEGIN # find unprimable numbers - numbers which can't be made into a prime by changing one digit #
# construct a sieve of primes up to max prime #
PR read "primes.incl.a68" PR
Line 226:
)
OD
END</langsyntaxhighlight>
{{out}}
<pre>
Line 245:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">unprimeable?: function [n][
if prime? n -> return false
nd: to :string n
Line 274:
print first.n: 35 unprimeables
print ""
print ["600th unprimeable number:" last unprimeables]</langsyntaxhighlight>
 
{{out}}
Line 285:
=={{header|C}}==
{{trans|C++}}
<langsyntaxhighlight lang="c">#include <assert.h>
#include <locale.h>
#include <stdbool.h>
Line 425:
printf("Least unprimeable number ending in %u: %'u\n" , i, lowest[i]);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 445:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cstdint>
#include "prime_sieve.hpp"
Line 514:
std::cout << "Least unprimeable number ending in " << i << ": " << lowest[i] << '\n';
return 0;
}</langsyntaxhighlight>
 
Contents of prime_sieve.hpp:
<langsyntaxhighlight lang="cpp">#ifndef PRIME_SIEVE_HPP
#define PRIME_SIEVE_HPP
 
Line 568:
}
 
#endif</langsyntaxhighlight>
 
{{out}}
Line 589:
=={{header|D}}==
{{trans|Java}}
<langsyntaxhighlight lang="d">import std.algorithm;
import std.array;
import std.conv;
Line 688:
writefln(" %d is %,d", i, v);
}
}</langsyntaxhighlight>
{{out}}
<pre>First 35 unprimeable numbers:
Line 713:
===The function===
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)]
<langsyntaxhighlight lang="fsharp">
// Unprimeable numbers. Nigel Galloway: May 4th., 2021
let rec fN i g e l=seq{yield! [0..9]|>Seq.map(fun n->n*g+e+l); if g>1 then let g=g/10 in yield! fN(i+g*(e/g)) g (e%g) i}
let fG(n,g)=fN(n*(g/n)) n (g%n) 0|>Seq.exists(isPrime)
let uP()=let rec fN n g=seq{yield! {n..g-1}|>Seq.map(fun g->(n,g)); yield! fN(g)(g*10)} in fN 1 10|>Seq.filter(fG>>not)|>Seq.map snd
</syntaxhighlight>
</lang>
===The Task===
<langsyntaxhighlight lang="fsharp">
uP()|>Seq.take 35|>Seq.iter(printf "%d "); printfn ""
</syntaxhighlight>
</lang>
{{out}}
<pre>
200 204 206 208 320 322 324 325 326 328 510 512 514 515 516 518 530 532 534 535 536 538 620 622 624 625 626 628 840 842 844 845 846 848 890
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "600th unprimable number is %d" (uP()|>Seq.item 599)
</syntaxhighlight>
</lang>
{{out}}
<pre>
600th unprimable number is 5242
</pre>
<langsyntaxhighlight lang="fsharp">
[0..9]|>Seq.iter(fun n->printfn "first umprimable number ending in %d is %d" n (uP()|>Seq.find(fun g->n=g%10)))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 753:
===Optimized for optional part of task===
The above general implementation can complete all of the task but takes over 1min for the optional part. The following completes the optional part in 3secs.
<langsyntaxhighlight lang="fsharp">
let uPx x=let rec fN n g=seq{yield! {n+x..10..g-1}|>Seq.map(fun g->(max 1 n,g)); yield! fN(g)(g*10)} in fN 0 10|>Seq.filter(fG>>not)|>Seq.map snd
[0..9]|>Seq.iter(fun n->printfn "first umprimable number ending in %d is %d" n (uPx n|>Seq.head))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 773:
=={{header|Factor}}==
{{works with|Factor|0.99 2019-10-06}}
<langsyntaxhighlight lang="factor">USING: assocs formatting io kernel lists lists.lazy
lists.lazy.examples math math.functions math.primes math.ranges
math.text.utils prettyprint sequences tools.memory.private ;
Line 805:
 
"The first unprimeable number ending with" print
first-digits [ commas " %d: %9s\n" printf ] assoc-each</langsyntaxhighlight>
{{out}}
<pre>
Line 827:
</pre>
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
Function isprime(n As Ulongint) As boolean
If (n=2) Or (n=3) Then Return 1
Line 879:
Next z
sleep
</syntaxhighlight>
</lang>
<pre>
First 35
Line 898:
=={{header|Go}}==
Simple brute force (no sieves, memoization or bigint.ProbablyPrime) as there is not much need for speed here.
<langsyntaxhighlight lang="go">package main
 
import (
Line 984:
fmt.Printf(" %d is: %9s\n", i, commatize(firstNum[i]))
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,005:
</pre>
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Lens ((.~), ix, (&))
import Data.Numbers.Primes (isPrime)
import Data.List (find, intercalate)
Line 1,035:
lowest n = do
x <- find (\x -> x `mod` 10 == n) unPrimeable
pure (n, thousands $ show x)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,057:
=={{header|J}}==
Reshaping data is a strength of j.
<syntaxhighlight lang="j">
<lang J>
NB. replace concatenates at various ranks and in boxes to avoid fill
NB. the curtailed prefixes (}:\) with all of 0..9 (i.10) with the beheaded suffixes (}.\.)
Line 1,069:
 
assert 0 1 -: unprimable 193 200
</syntaxhighlight>
</lang>
<pre>
NB. test 2e6 integers for unprimability
Line 1,089:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
public class UnprimeableNumbers {
 
Line 1,185:
 
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,209:
=={{header|JavaScript}}==
Auxiliary function:
<langsyntaxhighlight lang="javascript">
Number.prototype.isPrime = function() {
let i = 2, num = this;
Line 1,220:
return true;
}
</syntaxhighlight>
</lang>
 
Core function:
<langsyntaxhighlight lang="javascript">
function isUnprimable(num) {
if (num < 100 || num.isPrime()) return false;
Line 1,237:
return true;
}
</syntaxhighlight>
</lang>
 
Main function for output:
<langsyntaxhighlight lang="javascript">
let unprimeables = [],
endings = new Array(10).fill('-'),
Line 1,270:
}
console.timeEnd('II');
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,301:
 
'''Preliminaries'''
<langsyntaxhighlight lang="jq">def digits: tostring | explode | map([.] | implode | tonumber);
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
</syntaxhighlight>
</lang>
'''Unprimeables'''
<syntaxhighlight lang="jq">
<lang jq>
def variants:
digits
Line 1,322:
 
def unprimeables:
range(4; infinite) | select(is_unprimeable);</langsyntaxhighlight>
 
'''The Tasks'''
<langsyntaxhighlight lang="jq">def task:
"First 35 unprimeables: ",
[limit(35; range(0;infinite) | select(is_unprimeable))],
Line 1,338:
;
 
task</langsyntaxhighlight>
{{out}}
<pre>
Line 1,362:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Primes, Lazy, Formatting
 
function isunprimeable(n)
Line 1,386:
println(" $dig ", lpad(format(n, commas=true), 9))
end
</langsyntaxhighlight>{{out}}
<pre>
First 35 unprimeables: (200 204 206 208 320 322 324 325 326 328 510 512 514 515 516 518 530 532 534 535 536 538 620 622 624 625 626 628 840 842 844 845 846 848 890)
Line 1,408:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">private const val MAX = 10000000
private val primes = BooleanArray(MAX)
 
Line 1,502:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>First 35 unprimeable numbers:
Line 1,522:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">-- FUNCS:
local function T(t) return setmetatable(t, {__index=table}) end
table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end
Line 1,571:
for i = 0, 9 do
print(" " .. i .. " is: " .. commafy(lowests[i]))
end</langsyntaxhighlight>
{{out}}
<pre>The first 35 unprimable numbers are:
Line 1,591:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[Unprimeable]
Unprimeable[in_Integer] := Module[{id, new, pos},
id = IntegerDigits[in];
Line 1,633:
 
lastdigit = IntegerDigits /* Last;
Print["Least unprimeable number ending in ", lastdigit[#], ": ", #] & /@ SortBy[out, lastdigit];</langsyntaxhighlight>
{{out}}
<pre>{200,204,206,208,320,322,324,325,326,328,510,512,514,515,516,518,530,532,534,535,536,538,620,622,624,625,626,628,840,842,844,845,846,848,890}
Line 1,649:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import strutils
 
const N = 10_000_000
Line 1,697:
while not n.isUmprimeable:
inc n, 10
echo "Lowest unprimeable number ending in ", d, " is ", ($n).insertSep(',')</langsyntaxhighlight>
 
{{out}}
Line 1,719:
{{trans|Go}} {{works with|Free Pascal}}{{works with|Delphi}}
Small improvement.When the check of value ending in "0" is not unprimable than I can jump over by 10, since the check already has checked those numbers ending in "1".."9".But in case of unprimable I am using a reduced version of the check<BR>Results in runtime reduced from 1.8 secs downto 0.667 now to 0.46
<langsyntaxhighlight lang="pascal">program unprimable;
{$IFDEF FPC}{$Mode Delphi}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
Line 1,930:
writeln('There are ',TotalCnt,' unprimable numbers upto ',n);
{$IFNDEF UNIX}readln;{$ENDIF}
end.</langsyntaxhighlight>
{{out}}
<pre style="font-size:84%">
Line 1,953:
Base 18= 2*3*3 :lowest digit 7 found first 10,921,015,789<BR>
bases that are prime find their different digits quite early.
<langsyntaxhighlight lang="pascal">program unprimable;
{$IFDEF FPC}
{$Mode Delphi}
Line 2,369:
writeln('There are ',TotalCnt,' unprimable numbers upto ',n);
setlength(Primes,0);
end.</langsyntaxhighlight>
{{out}}
<pre style="height:35ex">
Line 2,441:
{{trans|Raku}}
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 2,470:
while ($x += 10) { last if is_unprimeable($x) }
say "First unprimeable that ends with $_: " . sprintf "%9s", comma $x;
} 0..9;</langsyntaxhighlight>
{{out}}
<pre>First 35 unprimeables:
Line 2,490:
=={{header|Phix}}==
{{trans|Go}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</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;">"The first 35 unprimeable numbers are:\n"</span><span style="color: #0000FF;">)</span>
Line 2,543:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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 2,566:
=={{header|Pike}}==
Not the fastest way of doing this, but using string manipulation seemed like the obvious Pike way to do it.
<syntaxhighlight lang="pike">
<lang Pike>
bool is_unprimeable(int i)
{
Line 2,605:
write(" %s is: %9d\n", e, first_enders[e]);
}
}</langsyntaxhighlight>
Output:
<pre>
Line 2,626:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from itertools import count, islice
 
def primes(_cache=[2, 3]):
Line 2,677:
 
for i,v in enumerate(first):
print(f'{i} ending: {v}')</langsyntaxhighlight>
{{out}}
<pre>First 35:
Line 2,699:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
 
(require math/number-theory)
Line 2,745:
(check-equal? (primeable? 10) 11)
(check-true (unprimeable? 200))
(check-false (unprimeable? 201)))</langsyntaxhighlight>
 
{{out}}
Line 2,765:
(formerly Perl 6)
{{libheader|ntheory}}
<syntaxhighlight lang="raku" perl6line>use ntheory:from<Perl5> <is_prime>;
use Lingua::EN::Numbers;
 
Line 2,791:
print "First unprimeable that ends with {n}: " ~
sprintf "%9s\n", comma (n, *+10 … *).race.first: { .&is-unprimeable }
}</langsyntaxhighlight>
{{out}}
<pre>First 35 unprimeables:
Line 2,813:
 
With the addition of the computation of squared primes, &nbsp; the program now is about '''4''' times faster.
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays unprimeable numbers (non─negative integers). */
parse arg n x hp . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 35 /*Not specified? Then use the default.*/
Line 2,880:
end /*k*/ /* [↓] a prime (J) has been found. */
#= #+1; if #<=lim then @.#=j; !.j=1 /*bump prime count; assign prime to @. */
sq.#= j*j /*calculate square of J for fast WHILE.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
 
Line 2,903:
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">require 'prime'
 
def unprimable?(n)
digits = %w(0 1 2 3 4 5 6 7 8 9)
s = n.to_s
size = s.size
(size-1).downto(0) do |i|
digits.each do |d|
cand = s.dup
cand[i]=d
return false if cand.to_i.prime?
end
end
true
end
ups = Enumerator.new {|y| (1..).each{|n| y << n if unprimable?(n)} }
 
ar = ups.first(600)
puts "First 35 unprimables:", ar[0,35].join(" ")
puts "\n600th unprimable:", ar.last, ""
(0..9).each do |d|
print "First unprimeable with last digit #{d}: "
puts (1..).detect{|k| unprimable?(k*10+d)}*10 + d
end
</syntaxhighlight>
{{out}}
<pre>First 35 unprimables:
200 204 206 208 320 322 324 325 326 328 510 512 514 515 516 518 530 532 534 535 536 538 620 622 624 625 626 628 840 842 844 845 846 848 890
 
600th unprimable:
5242
 
First unprimeable with last digit 0: 200
First unprimeable with last digit 1: 595631
First unprimeable with last digit 2: 322
First unprimeable with last digit 3: 1203623
First unprimeable with last digit 4: 204
First unprimeable with last digit 5: 325
First unprimeable with last digit 6: 206
First unprimeable with last digit 7: 872897
First unprimeable with last digit 8: 208
First unprimeable with last digit 9: 212159
</langpre>
=={{header|Rust}}==
{{trans|C++}}
<langsyntaxhighlight lang="rust">// main.rs
mod bit_array;
mod prime_sieve;
Line 2,981 ⟶ 3,025:
println!("Least unprimeable number ending in {}: {}", i, lowest[i]);
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="rust">// prime_sieve.rs
use crate::bit_array;
 
Line 3,018 ⟶ 3,062:
!self.composite.get(n / 2 - 1)
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="rust">// bit_array.rs
pub struct BitArray {
array: Vec<u32>,
Line 3,043 ⟶ 3,087:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,063 ⟶ 3,107:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func is_unprimeable(n) {
var t = 10*floor(n/10)
for k in (t+1 .. t+9 `by` 2) {
Line 3,094 ⟶ 3,138:
say ("First unprimeable that ends with #{d}: ",
1..Inf -> lazy.map {|k| k*10 + d }.grep(is_unprimeable).first)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,116 ⟶ 3,160:
=={{header|Swift}}==
{{trans|Rust}}
<langsyntaxhighlight lang="swift">import Foundation
 
class BitArray {
Line 3,242 ⟶ 3,286:
let str = NumberFormatter.localizedString(from: number, number: .decimal)
print("Least unprimeable number ending in \(i): \(str)")
}</langsyntaxhighlight>
 
{{out}}
Line 3,265 ⟶ 3,309:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
import "./math" for Int
 
System.print("The first 35 unprimeable numbers are:")
Line 3,310 ⟶ 3,354:
System.print("The first unprimeable number that ends in:")
for (i in 0...10) System.print(" %(i) is: %(Fmt.dc(9, firstNum[i]))")</langsyntaxhighlight>
 
{{out}}
Line 3,333 ⟶ 3,377:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
Line 3,391 ⟶ 3,435:
];
];
]</langsyntaxhighlight>
 
{{out}}
Line 3,413 ⟶ 3,457:
{{trans|Sidef}}
{{libheader|GMP}} GNU Multiple Precision Arithmetic Library and fast prime checking
<langsyntaxhighlight lang="zkl">var [const] BI=Import("zklBigNum"); // libGMP
 
fcn isUnprimeable(n){ //--> n (!0) or Void, a filter
Line 3,428 ⟶ 3,472:
n
}
fcn isUnprimeableW{ [100..].tweak(isUnprimeable) } // --> iterator</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">isUnprimeableW().walk(35).concat(" ").println();
println("The 600th unprimeable number is: %,d".fmt(isUnprimeableW().drop(600).value));
 
Line 3,436 ⟶ 3,480:
{ d:=up%10; if(ups[d]==0){ ups[d]=up; if((s-=1)<=0) break; } }
println("The first unprimeable number that ends in:");
foreach n in (10){ println("%d is %8,d".fmt(n,ups[n])) }</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits