Update all new Tasks

This commit is contained in:
Ingy döt Net 2015-02-20 09:02:09 -05:00
parent 00a190b0a6
commit 91df62d461
5697 changed files with 93386 additions and 804 deletions

View file

@ -0,0 +1,8 @@
A [[wp:Almost prime|k-Almost-prime]] is a natural number <math>n</math> that is the product of <math>k</math> (possibly identical) primes.
So, for example, 1-almost-primes, where <math>k=1</math>, are the prime numbers themselves; 2-almost-primes are the [[Semiprime|semiprimes]].
The task is to write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for <math>1 <= K <= 5</math>.
;Cf.
* [[Semiprime]]
* [[:Category:Prime Numbers]]

View file

@ -0,0 +1,2 @@
---
note: Prime Numbers

View file

@ -0,0 +1,25 @@
with Prime_Numbers, Ada.Text_IO;
procedure Test_Kth_Prime is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
Out_Length: constant Positive := 10; -- 10 k-th almost primes
N: Positive; -- the "current number" to be checked
begin
for K in 1 .. 5 loop
Ada.Text_IO.Put("K =" & Integer'Image(K) &": ");
N := 2;
for I in 1 .. Out_Length loop
while Decompose(N)'Length /= K loop
N := N + 1;
end loop; -- now N is Kth almost prime;
Ada.Text_IO.Put(Integer'Image(Integer(N)));
N := N + 1;
end loop;
Ada.Text_IO.New_Line;
end loop;
end Test_Kth_Prime;

View file

@ -0,0 +1,27 @@
kprime(n,k) {
p:=2, f:=0
while( (f<k) && (p*p<=n) ) {
while ( 0==mod(n,p) ) {
n/=p
f++
}
p++
}
return f + (n>1) == k
}
k:=1, results:=""
while( k<=5 ) {
i:=2, c:=0, results:=results "k =" k ":"
while( c<10 ) {
if (kprime(i,k)) {
results:=results " " i
c++
}
i++
}
results:=results "`n"
k++
}
MsgBox % results

View file

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace AlmostPrime
{
class Program
{
static void Main(string[] args)
{
foreach (int k in Enumerable.Range(1, 5))
{
KPrime kprime = new KPrime() { K = k };
Console.WriteLine("k = {0}: {1}",
k, string.Join<int>(" ", kprime.GetFirstN(10)));
}
}
}
class KPrime
{
public int K { get; set; }
public bool IsKPrime(int number)
{
int primes = 0;
for (int p = 2; p * p <= number && primes < K; ++p)
{
while (number % p == 0 && primes < K)
{
number /= p;
++primes;
}
}
if (number > 1)
{
++primes;
}
return primes == K;
}
public List<int> GetFirstN(int n)
{
List<int> result = new List<int>();
for (int number = 2; result.Count < n; ++number)
{
if (IsKPrime(number))
{
result.Add(number);
}
}
return result;
}
}
}

View file

@ -0,0 +1,30 @@
#include <stdio.h>
int kprime(int n, int k)
{
int p, f = 0;
for (p = 2; f < k && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == k;
}
int main(void)
{
int i, c, k;
for (k = 1; k <= 5; k++) {
printf("k = %d:", k);
for (i = 2, c = 0; c < 10; i++)
if (kprime(i, k)) {
printf(" %d", i);
c++;
}
putchar('\n');
}
return 0;
}

View file

@ -0,0 +1,13 @@
(defun start ()
(loop for k from 1 to 5
do (format t "k = ~a: ~a~%" k (collect-k-almost-prime k))))
(defun collect-k-almost-prime (k &optional (d 2) (lst nil))
(cond ((= (length lst) 10) (reverse lst))
((= (?-primality d) k) (collect-k-almost-prime k (+ d 1) (cons d lst)))
(t (collect-k-almost-prime k (+ d 1) lst))))
(defun ?-primality (n &optional (d 2) (c 0))
(cond ((> d (isqrt n)) (+ c 1))
((zerop (rem n d)) (?-primality (/ n d) d (+ c 1)))
(t (?-primality n (+ d 1) c))))

View file

@ -0,0 +1,36 @@
import std.stdio, std.algorithm, std.traits;
Unqual!T[] decompose(T)(in T number) pure nothrow
in {
assert(number > 1);
} body {
typeof(return) result;
Unqual!T n = number;
for (Unqual!T i = 2; n % i == 0; n /= i)
result ~= i;
for (Unqual!T i = 3; n >= i * i; i += 2)
for (; n % i == 0; n /= i)
result ~= i;
if (n != 1)
result ~= n;
return result;
}
void main() {
enum outLength = 10; // 10 k-th almost primes.
foreach (immutable k; 1 .. 6) {
writef("K = %d: ", k);
auto n = 2; // The "current number" to be checked.
foreach (immutable i; 1 .. outLength + 1) {
while (n.decompose.length != k)
n++;
// Now n is K-th almost prime.
write(n, " ");
n++;
}
writeln;
}
}

View file

@ -0,0 +1,36 @@
package main
import "fmt"
func kPrime(n, k int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == k {
return false
}
nf++
n /= i
}
}
return nf == k
}
func gen(k, n int) []int {
r := make([]int, n)
n = 2
for i := range r {
for !kPrime(n, k) {
n++
}
r[i] = n
n++
}
return r
}
func main() {
for k := 1; k <= 5; k++ {
fmt.Println(k, gen(k, 10))
}
}

View file

@ -0,0 +1,18 @@
isPrime :: Integral a => a -> Bool
isPrime n = not $ any ((0 ==) . (mod n)) [2..(truncate $ sqrt $ fromIntegral n)]
primes :: [Integer]
primes = filter isPrime [2..]
isKPrime :: (Num a, Eq a) => a -> Integer -> Bool
isKPrime 1 n = isPrime n
isKPrime k n = any (isKPrime (k - 1)) sprimes
where
sprimes = map fst $ filter ((0 ==) . snd) $ map (divMod n) $ takeWhile (< n) primes
kPrimes :: (Num a, Eq a) => a -> [Integer]
kPrimes k = filter (isKPrime k) [2..]
main :: IO ()
main = flip mapM_ [1..5] $ \k ->
putStrLn $ "k = " ++ show k ++ ": " ++ (unwords $ map show (take 10 $ kPrimes k))

View file

@ -0,0 +1,10 @@
link "factors"
procedure main()
every writes(k := 1 to 5,": ") do
every writes(right(genKap(k),5)\10|"\n")
end
procedure genKap(k)
suspend (k = *factors(n := seq(q)), n)
end

View file

@ -0,0 +1,6 @@
(10 {. [:~.[:/:~[:,*/~)^:(i.5)~p:i.10
2 3 5 7 11 13 17 19 23 29
4 6 9 10 14 15 21 22 25 26
8 12 18 20 27 28 30 42 44 45
16 24 36 40 54 56 60 81 84 88
32 48 72 80 108 112 120 162 168 176

View file

@ -0,0 +1,10 @@
isalmostprime(n, k) = sum(values(factor(n))) == k
function almostprimes(N, k) # return first N almost-k primes
P = Array(Int, N)
i = 0; n = 2
while i < N
if isalmostprime(n, k); P[i += 1] = n; end
n += 1
end
return P
end

View file

@ -0,0 +1,14 @@
kprimes[k_,n_] :=
(* generates a list of the n smallest k-almost-primes *)
Module[{firstnprimes, runningkprimes = {}},
firstnprimes = Prime[Range[n]];
runningkprimes = firstnprimes;
Do[
runningkprimes =
Outer[Times, firstnprimes , runningkprimes ] // Flatten // Union // Take[#, n] & ;
(* only keep lowest n numbers in our running list *)
, {i, 1, k - 1}];
runningkprimes
]
(* now to create table with n=10 and k ranging from 1 to 5 *)
Table[Flatten[{"k = " <> ToString[i] <> ": ", kprimes[i, 10]}], {i,1,5}] // TableForm

View file

@ -0,0 +1,27 @@
class Kth_Prime {
function : native : kPrime(n : Int, k : Int) ~ Bool {
f := 0;
for (p := 2; f < k & p*p <= n; p+=1;) {
while (0 = n % p) {
n /= p; f+=1;
};
};
return f + ((n > 1) ? 1 : 0) = k;
}
function : Main(args : String[]) ~ Nil {
for (k := 1; k <= 5; k+=1;) {
"k = {$k}:"->Print();
c := 0;
for (i := 2; c < 10; i+=1;) {
if (kPrime(i, k)) {
" {$i}"->Print();
c+=1;
};
};
'\n'->Print();
};
}
}

View file

@ -0,0 +1,2 @@
almost(k)=my(n); for(i=1,10,while(bigomega(n++)!=k,); print1(n", "));
for(k=1,5,almost(k);print)

View file

@ -0,0 +1,26 @@
program AlmostPrime;
{$IFDEF FPC}
{$Mode Delphi}
{$ENDIF}
uses
primtrial;
var
i,K,cnt : longWord;
BEGIN
K := 1;
repeat
cnt := 0;
i := 2;
write('K=',K:2,':');
repeat
if isAlmostPrime(i,K) then
Begin
write(i:6,' ');
inc(cnt);
end;
inc(i);
until cnt = 9;
writeln;
inc(k);
until k > 10;
END.

View file

@ -0,0 +1,11 @@
sub is-k-almost-prime($n is copy, $k) returns Bool {
loop (my ($p, $f) = 2, 0; $f < $k && $p*$p <= $n; $p++) {
$n /= $p, $f++ while $n %% $p;
}
$f + ($n > 1) == $k;
}
for 1 .. 5 -> $k {
say .[^10]
given grep { is-k-almost-prime($_, $k) }, 2 .. *
}

View file

@ -0,0 +1,5 @@
constant factory = 0..* Z=> (0, 0, map { +factors($_) }, 2..*);
sub almost($n) { map *.key, grep *.value == $n, factory }
say almost($_)[^10] for 1..5;

View file

@ -0,0 +1,7 @@
use ntheory qw/factor/;
sub almost {
my($k,$n) = @_;
my $i = 1;
map { $i++ while scalar factor($i) != $k; $i++ } 1..$n;
}
say "$_ : ", join(" ", almost($_,10)) for 1..5;

View file

@ -0,0 +1,64 @@
use strict;
use warnings;
sub k_almost_prime;
for my $k ( 1 .. 5 ) {
my $almost = 0;
print join(", ", map {
1 until k_almost_prime ++$almost, $k;
"$almost";
} 1 .. 10), "\n";
}
sub nth_prime;
sub k_almost_prime {
my ($n, $k) = @_;
return if $n <= 1 or $k < 1;
my $which_prime = 0;
for my $count ( 1 .. $k ) {
while( $n % nth_prime $which_prime ) {
++$which_prime;
}
$n /= nth_prime $which_prime;
return if $n == 1 and $count != $k;
}
($n == 1) ? 1 : ();
}
BEGIN {
# This is loosely based on one of the python solutions
# to the RC Sieve of Eratosthenes task.
my @primes = (2, 3, 5, 7);
my $p_iter = 1;
my $p = $primes[$p_iter];
my $q = $p*$p;
my %sieve;
my $candidate = $primes[-1] + 2;
sub nth_prime {
my $n = shift;
return if $n < 0;
OUTER: while( $#primes < $n ) {
while( my $s = delete $sieve{$candidate} ) {
my $next = $s + $candidate;
$next += $s while exists $sieve{$next};
$sieve{$next} = $s;
$candidate += 2;
}
while( $candidate < $q ) {
push @primes, $candidate;
$candidate += 2;
next OUTER if exists $sieve{$candidate};
}
my $twop = 2 * $p;
my $next = $q + $twop;
$next += $twop while exists $sieve{$next};
$sieve{$next} = $twop;
$p = $primes[++$p_iter];
$q = $p * $p;
$candidate += 2;
}
return $primes[$n];
}
}

View file

@ -0,0 +1,27 @@
(de factor (N)
(make
(let
(D 2
L (1 2 2 . (4 2 4 2 4 6 2 6 .))
M (sqrt N) )
(while (>= M D)
(if (=0 (% N D))
(setq M
(sqrt (setq N (/ N (link D)))) )
(inc 'D (pop 'L)) ) )
(link N) ) ) )
(de almost (N)
(let (X 2 Y 0)
(make
(loop
(when (and (nth (factor X) N) (not (cdr @)))
(link X)
(inc 'Y) )
(T (= 10 Y) 'done)
(inc 'X) ) ) ) )
(for I 5
(println I '-> (almost I) ) )
(bye)

View file

@ -0,0 +1,20 @@
% almostPrime(K, +Take, List) succeeds if List can be unified with the
% first Take K-almost-primes.
% Notice that K need not be specified.
% To avoid having to cache or recompute the first Take primes, we define
% almostPrime/3 in terms of almostPrime/4 as follows:
%
almostPrime(K, Take, List) :-
% Compute the list of the first Take primes:
nPrimes(Take, Primes),
almostPrime(K, Take, Primes, List).
almostPrime(1, Take, Primes, Primes).
almostPrime(K, Take, Primes, List) :-
generate(2, K), % generate K >= 2
K1 is K - 1,
almostPrime(K1, Take, Primes, L),
multiplylist( Primes, L, Long),
sort(Long, Sorted), % uniquifies
take(Take, Sorted, List).

View file

@ -0,0 +1,40 @@
nPrimes( M, Primes) :- nPrimes( [2], M, Primes).
nPrimes( Accumulator, I, Primes) :-
next_prime(Accumulator, Prime),
append(Accumulator, [Prime], Next),
length(Next, N),
( N = I -> Primes = Next; nPrimes( Next, I, Primes)).
% next_prime(+Primes, NextPrime) succeeds if NextPrime is the next
% prime after a list, Primes, of consecutive primes starting at 2.
next_prime([2], 3).
next_prime([2|Primes], P) :-
last(Primes, PP),
P2 is PP + 2,
generate(P2, N),
1 is N mod 2, % odd
Max is floor(sqrt(N+1)), % round-off paranoia
forall( (member(Prime, [2|Primes]),
(Prime =< Max -> true
; (!, fail))), N mod Prime > 0 ),
!,
P = N.
% multiply( +A, +List, Answer )
multiply( A, [], [] ).
multiply( A, [X|Xs], [AX|As] ) :-
AX is A * X,
multiply(A, Xs, As).
% multiplylist( L1, L2, List ) succeeds if List is the concatenation of X * L2
% for successive elements X of L1.
multiplylist( [], B, [] ).
multiplylist( [A|As], B, List ) :-
multiply(A, B, L1),
multiplylist(As, B, L2),
append(L1, L2, List).
take(N, List, Head) :-
length(Head, N),
append(Head,X,List).

View file

@ -0,0 +1,28 @@
%%%%% compatibility section %%%%%
:- if(current_prolog_flag(dialect, yap)).
generate(Min, I) :- between(Min, inf, I).
append([],L,L).
append([X|Xs], L, [X|Ls]) :- append(Xs,L,Ls).
:- endif.
:- if(current_prolog_flag(dialect, swi)).
generate(Min, I) :- between(Min, inf, I).
:- endif.
:- if(current_prolog_flag(dialect, yap)).
append([],L,L).
append([X|Xs], L, [X|Ls]) :- append(Xs,L,Ls).
last([X], X).
last([_|Xs],X) :- last(Xs,X).
:- endif.
:- if(current_prolog_flag(dialect, gprolog)).
generate(Min, I) :-
current_prolog_flag(max_integer, Max),
between(Min, Max, I).
:- endif.

View file

@ -0,0 +1,19 @@
from prime_decomposition import decompose
from itertools import islice, count
try:
from functools import reduce
except:
pass
def almostprime(n, k=2):
d = decompose(n)
try:
terms = [next(d) for i in range(k)]
return reduce(int.__mul__, terms, 1) == n
except:
return False
if __name__ == '__main__':
for k in range(1,6):
print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))

1
Task/Almost-prime/README Normal file
View file

@ -0,0 +1 @@
Data source: http://rosettacode.org/wiki/Almost_prime

View file

@ -0,0 +1,33 @@
/*REXX program displays the N numbers of the first K k-almost primes*/
parse arg N K . /*get the arguments from the C.L.*/
if N=='' then N=10 /*No N? Then use the default.*/
if K=='' then K=5 /* " K? " " " " */
/* [↓] display one line per K.*/
do m=1 for K; $=2**m; fir=$ /*generate the 1st k_almost prime*/
#=1; if #==N then leave /*# k-almost primes; 'nuff found?*/
sec=3*(2**(m-1)); $=$ sec; #=2 /*generate the 2nd k-almost prime*/
do j=fir+fir+1 until #==N /*process an almost-prime N times*/
if #factr(j)\==m then iterate /*not the correct k-almost prime?*/
#=#+1 /*bump the k-almost prime counter*/
$=$ j /*append k-almost prime to list. */
end /*j*/ /* [↑] gen N k-almost primes.*/
say N right(m,4)"-almost primes:" $ /*display the k-almost primes.*/
end /*m*/ /* [↑] display a line for each K*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────#FACTR subroutine───────────────────*/
#factr: procedure;parse arg x 1 z; f=0 /*defines X and Z to the arg.*/
if x<2 then return 0 /*invalid number? Then return 0.*/
do j=2 to 5; if j\==4 then call .#factr; end /*fast factoring.*/
j=5 /*start were we left off (J=5). */
do y=0 by 2; j=j+2 + y//4 /*insure it's not divisible by 3.*/
if right(j,1)==5 then iterate /*fast check for divisible by 5.*/
if j>z then leave /*number reduced to a wee number?*/
call .#factr /*go add other factors to count. */
end /*y*/ /* [↑] find all factors in X. */
return max(f,1) /*if prime (f==0), then return 1.*/
/*──────────────────────────────────.#FACTR subroutine──────────────────*/
.#factr: do f=f+1 while z//j==0 /*keep dividing until we can't. */
z=z%j /*perform an (%) integer divide.*/
end /*while*/ /* [↑] whittle down the Z num.*/
f=f-1 /*adjust the count of factors. */
return

View file

@ -0,0 +1,35 @@
/*REXX program displays the N numbers of the first K k-almost primes*/
parse arg N K . /*get the arguments from the C.L.*/
if N=='' then N=10 /*No N? Then use the default.*/
if K=='' then K=5 /* " K? " " " " */
/* [↓] display one line per K.*/
do m=1 for K; $=2**m; fir=$ /*generate the 1st k_almost prime*/
#=1; if #==N then leave /*# k-almost primes; 'nuff found?*/
sec=3*(2**(m-1)); $=$ sec; #=2 /*generate the 2nd k-almost prime*/
do j=fir+fir+1 until #==N /*process an almost-prime N times*/
if #factL(j,m)\==m then iterate /*not the correct k-almost prime?*/
#=#+1 /*bump the k-almost prime counter*/
$=$ j /*append k-almost prime to list. */
end /*j*/ /* [↑] gen N k-almost primes.*/
say N right(m,4)"-almost primes:" $ /*display the k-almost primes.*/
end /*m*/ /* [↑] display a line for each K*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────#FACTL subroutine───────────────────*/
#factL: procedure; parse arg x 1 z,L /*defines X and Z to the arg.*/
f=0; if x<2 then return 0 /*invalid number? Then return 0.*/
do j=2 to 5; if j\==4 then call .#factL; end /*fast factoring.*/
if f>L then return f /*#factors > L ? Then too many.*/
j=5 /*start were we left off (J=5). */
do y=0 by 2; j=j+2 + y//4 /*insure it's not divisible by 3.*/
if right(j,1)==5 then iterate /*fast check for divisible by 5.*/
if j>z then leave /*number reduced to a wee number?*/
call .#factL /*go add other factors to count. */
if f>L then return f /*#factors > L ? Then too many.*/
end /*y*/ /* [↑] find all factors in X. */
return max(f,1) /*if prime (f==0), then return 1.*/
/*──────────────────────────────────.#FACTL subroutine──────────────────*/
.#factL: do f=f+1 while z//j==0 /*keep dividing until we can't. */
z=z%j /*perform an (%) integer divide.*/
end /*while*/ /* [↑] whittle down the Z num.*/
f=f-1 /*adjust the count of factors. */
return

View file

@ -0,0 +1,25 @@
#lang racket
(require (only-in math/number-theory factorize))
(define ((k-almost-prime? k) n)
(= k (for/sum ((f (factorize n))) (cadr f))))
(define KAP-table-values
(for/list ((k (in-range 1 (add1 5))))
(define kap? (k-almost-prime? k))
(for/list ((j (in-range 10)) (i (sequence-filter kap? (in-naturals 1))))
i)))
(define (format-table t)
(define longest-number-length
(add1 (order-of-magnitude (argmax order-of-magnitude (cons (length t) (apply append t))))))
(define (fmt-val v) (~a v #:width longest-number-length #:align 'right))
(string-join
(for/list ((r t) (k (in-naturals 1)))
(string-append
(format "║ k = ~a║ " (fmt-val k))
(string-join (for/list ((c r)) (fmt-val c)) "| ")
""))
"\n"))
(displayln (format-table KAP-table-values))

View file

@ -0,0 +1,12 @@
require 'prime'
def almost_primes(k=2)
return to_enum(:almost_primes, k) unless block_given?
n = 0
loop do
n += 1
yield n if n.prime_division.map( &:last ).inject( &:+ ) == k
end
end
(1..5).each{|k| puts almost_primes(k).take(10).join(", ")}

View file

@ -0,0 +1,4 @@
require 'prime'
p ar = pr = Prime.take(10)
4.times{p ar = ar.product(pr).map{|(a,b)| a*b}.uniq.sort.take(10)}

View file

@ -0,0 +1,39 @@
fn is_kprime(n: usize, k: usize) -> bool {
let mut primes = 0us;
let mut f = 2us;
let mut rem = n;
while primes < k && rem > 1{
while (rem % f) == 0 && rem > 1{
rem /= f;
primes += 1;
}
f += 1;
}
rem == 1 && primes == k
}
struct KPrimeGen {
k: usize,
n: usize,
}
impl Iterator for KPrimeGen {
type Item = usize;
fn next(&mut self) -> Option<usize> {
self.n += 1;
while !is_kprime(self.n, self.k) {
self.n += 1;
}
Some(self.n)
}
}
fn kprime_generator(k: usize) -> KPrimeGen {
KPrimeGen {k: k, n: 1}
}
fn main() {
for k in 1us..6 {
println!("{}: {:?}", k, kprime_generator(k).take(10).collect::<Vec<_>>());
}
}

View file

@ -0,0 +1,16 @@
def isKPrime(n: Int, k: Int, d: Int = 2): Boolean = (n, k, d) match {
case (n, k, _) if n == 1 => k == 0
case (n, _, d) if n % d == 0 => isKPrime(n / d, k - 1, d)
case (_, _, _) => isKPrime(n, k, d + 1)
}
def kPrimeStream(k: Int): Stream[Int] = {
def loop(n: Int): Stream[Int] =
if (isKPrime(n, k)) n #:: loop(n+ 1)
else loop(n + 1)
loop(2)
}
for (k <- 1 to 5) {
println( s"$k: [${ kPrimeStream(k).take(10) mkString " " }]" )
}

View file

@ -0,0 +1,31 @@
package require Tcl 8.6
package require math::numtheory
proc firstNprimes n {
for {set result {};set i 2} {[llength $result] < $n} {incr i} {
if {[::math::numtheory::isprime $i]} {
lappend result $i
}
}
return $result
}
proc firstN_KalmostPrimes {n k} {
set p [firstNprimes $n]
set i [lrepeat $k 0]
set c {}
while true {
dict set c [::tcl::mathop::* {*}[lmap j $i {lindex $p $j}]] ""
for {set x 0} {$x < $k} {incr x} {
lset i $x [set xx [expr {([lindex $i $x] + 1) % $n}]]
if {$xx} break
}
if {$x == $k} break
}
return [lrange [lsort -integer [dict keys $c]] 0 [expr {$n - 1}]]
}
for {set K 1} {$K <= 5} {incr K} {
puts "$K => [firstN_KalmostPrimes 10 $K]"
}