tasks a-s

This commit is contained in:
Ingy döt Net 2013-04-10 23:57:08 -07:00
parent 47bf37c096
commit b83f433714
12433 changed files with 156208 additions and 123 deletions

View file

@ -0,0 +1,7 @@
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example: 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Write a function which returns an [[array]] or [[Collections|collection]] which contains the prime decomposition of a given number, n, greater than 1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from [[Primality by Trial Division|trial division]] or the [[Sieve of Eratosthenes]].
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).

View file

@ -0,0 +1,4 @@
---
category:
- Arbitrary precision
note: Prime Numbers

View file

@ -0,0 +1,53 @@
class ZMLA_ROSETTA definition
public
create public .
public section.
types:
enumber TYPE N LENGTH 60,
listof_enumber TYPE TABLE OF enumber .
class-methods FACTORS
importing
value(N) type ENUMBER
exporting
value(ORET) type LISTOF_ENUMBER .
protected section.
private section.
ENDCLASS.
CLASS ZMLA_ROSETTA IMPLEMENTATION.
* <SIGNATURE>---------------------------------------------------------------------------------------+
* | Static Public Method ZMLA_ROSETTA=>FACTORS
* +-------------------------------------------------------------------------------------------------+
* | [--->] N TYPE ENUMBER
* | [<---] ORET TYPE LISTOF_ENUMBER
* +--------------------------------------------------------------------------------------</SIGNATURE>
method FACTORS.
CLEAR oret.
WHILE n mod 2 = 0.
n = n / 2.
APPEND 2 to oret.
ENDWHILE.
DATA: lim type enumber,
i type enumber.
lim = sqrt( n ).
i = 3.
WHILE i <= lim.
WHILE n mod i = 0.
APPEND i to oret.
n = n / i.
lim = sqrt( n ).
ENDWHILE.
i = i + 2.
ENDWHILE.
IF n > 1.
APPEND n to oret.
ENDIF.
endmethod.
ENDCLASS.

View file

@ -0,0 +1,13 @@
(include-book "arithmetic-3/top" :dir :system)
(defun prime-factors-r (n i)
(declare (xargs :mode :program))
(cond ((or (zp n) (zp (- n i)) (zp i) (< i 2) (< n 2))
(list n))
((= (mod n i) 0)
(cons i (prime-factors-r (floor n i) 2)))
(t (prime-factors-r n (1+ i)))))
(defun prime-factors (n)
(declare (xargs :mode :program))
(prime-factors-r n 2))

View file

@ -0,0 +1,103 @@
#IF long int possible THEN #
MODE LINT = LONG INT;
LINT lmax int = long max int;
OP LLENG = (INT i)LINT: LENG i,
LSHORTEN = (LINT i)INT: SHORTEN i;
#ELSE
MODE LINT = INT;
LINT lmax int = max int;
OP LLENG = (INT i)LINT: i,
LSHORTEN = (LINT i)INT: i;
FI#
OP LLONG = (INT i)LINT: LLENG i;
MODE YIELDLINT = PROC(LINT)VOID;
PROC (LINT, YIELDLINT)VOID gen decompose;
INT upb cache = bits width;
BITS cache := 2r0;
BITS cached := 2r0;
PROC is prime = (LINT n)BOOL: (
BOOL
has factor := FALSE,
out := TRUE;
# FOR LINT factor IN # gen decompose(n, # ) DO ( #
## (LINT factor)VOID:(
IF has factor THEN out := FALSE; GO TO done FI;
has factor := TRUE
# OD # ));
done: out
);
PROC is prime cached := (LINT n)BOOL: (
LINT l half n = n OVER LLONG 2 - LLONG 1;
IF l half n <= LLENG upb cache THEN
INT half n = LSHORTEN l half n;
IF half n ELEM cached THEN
BOOL(half n ELEM cache)
ELSE
BOOL out = is prime(n);
BITS mask = 2r1 SHL (upb cache - half n);
cached := cached OR mask;
IF out THEN cache := cache OR mask FI;
out
FI
ELSE
is prime(n) # above useful cache limit #
FI
);
PROC gen primes := (YIELDLINT yield)VOID:(
yield(LLONG 2);
LINT n := LLONG 3;
WHILE n < l maxint - LLONG 2 DO
yield(n);
n +:= LLONG 2;
WHILE n < l maxint - LLONG 2 AND NOT is prime cached(n) DO
n +:= LLONG 2
OD
OD
);
# PROC # gen decompose := (LINT in n, YIELDLINT yield)VOID: (
LINT n := in n;
# FOR LINT p IN # gen primes( # ) DO ( #
## (LINT p)VOID:
IF p*p > n THEN
GO TO done
ELSE
WHILE n MOD p = LLONG 0 DO
yield(p);
n := n OVER p
OD
FI
# OD # );
done:
IF n > LLONG 1 THEN
yield(n)
FI
);
main:(
# FOR LINT m IN # gen primes( # ) DO ( #
## (LINT m)VOID:(
LINT p = LLONG 2 ** LSHORTEN m - LLONG 1;
print(("2**",whole(m,0),"-1 = ",whole(p,0),", with factors:"));
# FOR LINT factor IN # gen decompose(p, # ) DO ( #
## (LINT factor)VOID:
print((" ",whole(factor,0)))
# OD # );
print(new line);
IF m >= LLONG 59 THEN GO TO done FI
# OD # ));
done: EMPTY
)

View file

@ -0,0 +1,14 @@
function pfac(n, r, f){
r = ""; f = 2
while (f <= n) {
while(!(n % f)) {
n = n / f
r = r " " f
}
f = f + 2 - (f == 2)
}
return r
}
# For each line of input, print the prime factors.
{ print pfac($1) }

View file

@ -0,0 +1,60 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Prime is
generic
type Number is private;
Zero : Number;
One : Number;
Two : Number;
with function Image (X : Number) return String is <>;
with function "+" (X, Y : Number) return Number is <>;
with function "/" (X, Y : Number) return Number is <>;
with function "mod" (X, Y : Number) return Number is <>;
with function ">=" (X, Y : Number) return Boolean is <>;
package Prime_Numbers is
type Number_List is array (Positive range <>) of Number;
function Decompose (N : Number) return Number_List;
procedure Put (List : Number_List);
end Prime_Numbers;
package body Prime_Numbers is
function Decompose (N : Number) return Number_List is
Size : Natural := 0;
M : Number := N;
K : Number := Two;
begin
-- Estimation of the result length from above
while M >= Two loop
M := (M + One) / Two;
Size := Size + 1;
end loop;
M := N;
-- Filling the result with prime numbers
declare
Result : Number_List (1..Size);
Index : Positive := 1;
begin
while N >= K loop -- Divisors loop
while Zero = (M mod K) loop -- While divides
Result (Index) := K;
Index := Index + 1;
M := M / K;
end loop;
K := K + One;
end loop;
return Result (1..Index - 1);
end;
end Decompose;
procedure Put (List : Number_List) is
begin
for Index in List'Range loop
Put (Image (List (Index)));
end loop;
end Put;
end Prime_Numbers;
package Integer_Numbers is new Prime_Numbers (Natural, 0, 1, 2, Positive'Image);
use Integer_Numbers;
begin
Put (Decompose (12));
end Test_Prime;

View file

@ -0,0 +1,18 @@
MsgBox % factor(8388607) ; 47 * 178481
factor(n)
{
If (n = 1)
Return
f = 2
While (f <= n)
{
If (Mod(n, f) = 0)
{
next := factor(n / f)
factors = %f%`n%next%
Return factors
}
f++
}
}

View file

@ -0,0 +1,4 @@
& 211p > : 1 - #v_ 25*, @ > 11g:. / v
> : 11g %!|
> 11g 1+ 11p v
^ <

View file

@ -0,0 +1,2 @@
blsq ) 12fC
{2 2 3}

View file

@ -0,0 +1,85 @@
#include <iostream>
#include <gmpxx.h>
// This function template works for any type representing integers or
// nonnegative integers, and has the standard operator overloads for
// arithmetic and comparison operators, as well as explicit conversion
// from int.
//
// OutputIterator must be an output iterator with value_type Integer.
// It receives the prime factors.
template<typename Integer, typename OutputIterator>
void decompose(Integer n, OutputIterator out)
{
Integer i(2);
while (n != 1)
{
while (n % i == Integer(0))
{
*out++ = i;
n /= i;
}
++i;
}
}
// this is an output iterator similar to std::ostream_iterator, except
// that it outputs the separation string *before* the value, but not
// before the first value (i.e. it produces an infix notation).
template<typename T> class infix_ostream_iterator:
public std::iterator<T, std::output_iterator_tag>
{
class Proxy;
friend class Proxy;
class Proxy
{
public:
Proxy(infix_ostream_iterator& iter): iterator(iter) {}
Proxy& operator=(T const& value)
{
if (!iterator.first)
{
iterator.stream << iterator.infix;
}
iterator.stream << value;
}
private:
infix_ostream_iterator& iterator;
};
public:
infix_ostream_iterator(std::ostream& os, char const* inf):
stream(os),
first(true),
infix(inf)
{
}
infix_ostream_iterator& operator++() { first = false; return *this; }
infix_ostream_iterator operator++(int)
{
infix_ostream_iterator prev(*this);
++*this;
return prev;
}
Proxy operator*() { return Proxy(*this); }
private:
std::ostream& stream;
bool first;
char const* infix;
};
int main()
{
std::cout << "please enter a positive number: ";
mpz_class number;
std::cin >> number;
if (number <= 0)
std::cout << "this number is not positive!\n;";
else
{
std::cout << "decomposition: ";
decompose(number, infix_ostream_iterator<mpz_class>(std::cout, " * "));
std::cout << "\n";
}
}

View file

@ -0,0 +1,171 @@
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef uint32_t pint;
typedef uint64_t xint;
typedef unsigned int uint;
#define PRIuPINT PRIu32 /* printf macro for pint */
#define PRIuXINT PRIu64 /* printf macro for xint */
#define MAX_FACTORS 63 /* because 2^64 is too large for xint */
uint8_t *pbits;
#define MAX_PRIME (~(pint)0)
#define MAX_PRIME_SQ 65535U
#define PBITS (MAX_PRIME / 30 + 1)
pint next_prime(pint);
int is_prime(xint);
void sieve(pint);
uint8_t bit_pos[30] = {
0, 1<<0, 0, 0, 0, 0,
0, 1<<1, 0, 0, 0, 1<<2,
0, 1<<3, 0, 0, 0, 1<<4,
0, 1<<5, 0, 0, 0, 1<<6,
0, 0, 0, 0, 0, 1<<7,
};
uint8_t rem_num[] = { 1, 7, 11, 13, 17, 19, 23, 29 };
void init_primes()
{
FILE *fp;
pint s, tgt = 4;
if (!(pbits = malloc(PBITS))) {
perror("malloc");
exit(1);
}
if ((fp = fopen("primebits", "r"))) {
fread(pbits, 1, PBITS, fp);
fclose(fp);
return;
}
memset(pbits, 255, PBITS);
for (s = 7; s <= MAX_PRIME_SQ; s = next_prime(s)) {
if (s > tgt) {
tgt *= 2;
fprintf(stderr, "sieve %"PRIuPINT"\n", s);
}
sieve(s);
}
fp = fopen("primebits", "w");
fwrite(pbits, 1, PBITS, fp);
fclose(fp);
}
int is_prime(xint x)
{
pint p;
if (x > 5) {
if (x < MAX_PRIME)
return pbits[x/30] & bit_pos[x % 30];
for (p = 2; p && (xint)p * p <= x; p = next_prime(p))
if (x % p == 0) return 0;
return 1;
}
return x == 2 || x == 3 || x == 5;
}
void sieve(pint p)
{
unsigned char b[8];
off_t ofs[8];
int i, q;
for (i = 0; i < 8; i++) {
q = rem_num[i] * p;
b[i] = ~bit_pos[q % 30];
ofs[i] = q / 30;
}
for (q = ofs[1], i = 7; i; i--)
ofs[i] -= ofs[i-1];
for (ofs[0] = p, i = 1; i < 8; i++)
ofs[0] -= ofs[i];
for (i = 1; q < PBITS; q += ofs[i = (i + 1) & 7])
pbits[q] &= b[i];
}
pint next_prime(pint p)
{
off_t addr;
uint8_t bits, rem;
if (p > 5) {
addr = p / 30;
bits = bit_pos[ p % 30 ] << 1;
for (rem = 0; (1 << rem) < bits; rem++);
while (pbits[addr] < bits || !bits) {
if (++addr >= PBITS) return 0;
bits = 1;
rem = 0;
}
if (addr >= PBITS) return 0;
while (!(pbits[addr] & bits)) {
rem++;
bits <<= 1;
}
return p = addr * 30 + rem_num[rem];
}
switch(p) {
case 2: return 3;
case 3: return 5;
case 5: return 7;
}
return 2;
}
int decompose(xint n, xint *f)
{
pint p = 0;
int i = 0;
/* check small primes: not strictly necessary */
if (n <= MAX_PRIME && is_prime(n)) {
f[0] = n;
return 1;
}
while (n >= (xint)p * p) {
if (!(p = next_prime(p))) break;
while (n % p == 0) {
n /= p;
f[i++] = p;
}
}
if (n > 1) f[i++] = n;
return i;
}
int main()
{
int i, len;
pint p = 0;
xint f[MAX_FACTORS], po;
init_primes();
for (p = 1; p < 64; p++) {
po = (1LLU << p) - 1;
printf("2^%"PRIuPINT" - 1 = %"PRIuXINT, p, po);
fflush(stdout);
if ((len = decompose(po, f)) > 1)
for (i = 0; i < len; i++)
printf(" %c %"PRIuXINT, i?'x':'=', f[i]);
putchar('\n');
}
return 0;
}

View file

@ -0,0 +1,107 @@
#include <limits.h>
#include <stdio.h>
#include <math.h>
typedef enum{false=0, true=1}bool;
const int max_lint = LONG_MAX;
typedef long long int lint;
#assert sizeof_long_long_int (LONG_MAX>=8) /* XXX */
/* the following line is the only time I have ever required "auto" */
#define FOR(i,iterator) auto bool lambda(i); yield_init = (void *)&lambda; iterator; bool lambda(i)
#define DO {
#define YIELD(x) if(!yield(x))return
#define BREAK return false
#define CONTINUE return true
#define OD CONTINUE; }
/* Warning: _Most_ FOR(,){ } loops _must_ have a CONTINUE as the last statement.
* Otherwise the lambda will return random value from stack, and may terminate early */
typedef void iterator, lint_iterator; /* hint at procedure purpose */
static volatile void *yield_init; /* not thread safe */
#define YIELDS(type) bool (*yield)(type) = yield_init
typedef unsigned int bits;
#define ELEM(shift, bits) ( (bits >> shift) & 0b1 )
bits cache = 0b0, cached = 0b0;
const lint upb_cache = 8 * sizeof(cache);
lint_iterator decompose(lint); /* forward declaration */
bool is_prime(lint n){
bool has_factor = false, out = true;
/* for factor in decompose(n) do */
FOR(lint factor, decompose(n)){
if( has_factor ){ out = false; BREAK; }
has_factor = true;
CONTINUE;
}
return out;
}
bool is_prime_cached (lint n){
lint half_n = n / 2 - 2;
if( half_n <= upb_cache){
/* dont cache the initial four, nor the even numbers */
if (ELEM(half_n,cached)){
return ELEM(half_n,cache);
} else {
bool out = is_prime(n);
cache = cache | out << half_n;
cached = cached | 0b1 << half_n;
return out;
}
} else {
return is_prime(n);
}
}
lint_iterator primes (){
YIELDS(lint);
YIELD(2);
lint n = 3;
while( n < max_lint - 2 ){
YIELD(n);
n += 2;
while( n < max_lint - 2 && ! is_prime_cached(n) ){
n += 2;
}
}
}
lint_iterator decompose (lint in_n){
YIELDS(lint);
lint n = in_n;
/* for p in primes do */
FOR(lint p, primes()){
if( p*p > n ){
BREAK;
} else {
while( n % p == 0 ){
YIELD(p);
n = n / p;
}
}
CONTINUE;
}
if( n > 1 ){
YIELD(n);
}
}
main(){
FOR(lint m, primes()){
lint p = powl(2, m) - 1;
printf("2**%lld-1 = %lld, with factors:",m,p);
FOR(lint factor, decompose(p)){
printf(" %lld",factor);
fflush(stdout);
CONTINUE;
}
printf("\n",m);
if( m >= 59 )BREAK;
CONTINUE;
}
}

View file

@ -0,0 +1,73 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint32_t pint;
typedef uint64_t xint;
typedef unsigned int uint;
int is_prime(xint);
inline int next_prime(pint p)
{
if (p == 2) return 3;
for (p += 2; p > 1 && !is_prime(p); p += 2);
if (p == 1) return 0;
return p;
}
int is_prime(xint n)
{
# define NCACHE 256
# define S (sizeof(uint) * 2)
static uint cache[NCACHE] = {0};
pint p = 2;
int ofs, bit = -1;
if (n < NCACHE * S) {
ofs = n / S;
bit = 1 << ((n & (S - 1)) >> 1);
if (cache[ofs] & bit) return 1;
}
do {
if (n % p == 0) return 0;
if (p * p > n) break;
} while ((p = next_prime(p)));
if (bit != -1) cache[ofs] |= bit;
return 1;
}
int decompose(xint n, pint *out)
{
int i = 0;
pint p = 2;
while (n > p * p) {
while (n % p == 0) {
out[i++] = p;
n /= p;
}
if (!(p = next_prime(p))) break;
}
if (n > 1) out[i++] = n;
return i;
}
int main()
{
int i, j, len;
xint z;
pint out[100];
for (i = 2; i < 64; i = next_prime(i)) {
z = (1ULL << i) - 1;
printf("2^%d - 1 = %llu = ", i, z);
fflush(stdout);
len = decompose(z, out);
for (j = 0; j < len; j++)
printf("%u%s", out[j], j < len - 1 ? " x " : "\n");
}
return 0;
}

View file

@ -0,0 +1,11 @@
;;; No stack consuming algorithm
(defn factors
"Return a list of factors of N."
([n]
(factors n 2 ()))
([n k acc]
(if (= 1 n)
acc
(if (= 0 (rem n k))
(recur (quot n k) k (cons k acc))
(recur n (inc k) acc)))))

View file

@ -0,0 +1,8 @@
;;; Recursive algorithm
(defun factor (n)
"Return a list of factors of N."
(when (> n 1)
(loop with max-d = (isqrt n)
for d = 2 then (if (evenp d) (+ d 1) (+ d 2)) do
(cond ((> d max-d) (return (list n))) ; n is prime
((zerop (rem n d)) (return (cons d (factor (truncate n d)))))))))

View file

@ -0,0 +1,37 @@
import std.traits: Unqual;
Unqual!T[] decompose(T)(T number) /*pure nothrow*/
in {
assert(number > 1);
} body {
alias UT = Unqual!T;
typeof(return) result;
UT n = number;
for (UT i = 2; n % i == 0;) {
result ~= i;
n /= i;
}
for (UT i = 3; n >= i * i; i += 2) {
while (n % i == 0) {
result ~= i;
n /= i;
}
}
if (n != 1)
result ~= n;
return result;
}
void main() {
import std.stdio, std.bigint, std.algorithm;
foreach (immutable n; 2 .. 10)
writeln(decompose(n));
writeln(decompose(1023 * 1024));
writeln(decompose(BigInt(2 * 3 * 5 * 7 * 11 * 11 * 13 * 17)));
writeln(decompose(BigInt(16860167264933UL) * 179951));
writeln(group(decompose(BigInt(2) ^^ 100_000)));
}

View file

@ -0,0 +1,29 @@
def primes := {
var primesCache := [2]
/** A collection of all prime numbers. */
def primes {
to iterate(f) {
primesCache.iterate(f)
for x in (int > primesCache.last()) {
if (isPrime(x)) {
f(primesCache.size(), x)
primesCache with= x
}
}
}
}
}
def primeDecomposition(var x :(int > 0)) {
var factors := []
for p in primes {
while (x % p <=> 0) {
factors with= p
x //= p
}
if (x <=> 1) {
break
}
}
return factors
}

View file

@ -0,0 +1,10 @@
% no stack consuming version
factors(N) ->
factors(N,2,[]).
factors(1,_,Acc) -> Acc;
factors(N,K,Acc) when N rem K == 0 ->
factors(N div K,K, [K|Acc]);
factors(N,K,Acc) ->
factors(N,K+1,Acc).

View file

@ -0,0 +1,2 @@
[2[\$@$$*@>~][\$@$@$@$@\/*=$[%$." "$@\/\0~]?~[1+1|]?]#%.]d:
27720d;! {2 2 2 3 3 5 7 11}

View file

@ -0,0 +1,5 @@
USING: io kernel math math.parser math.primes.factors sequences ;
27720 factors
[ number>string ] map
" " join print ;

View file

@ -0,0 +1,9 @@
: decomp ( n -- )
2
begin 2dup dup * >=
while 2dup /mod swap
if drop 1+ 1 or \ next odd number
else -rot nip dup .
then
repeat
drop . ;

View file

@ -0,0 +1,31 @@
module PrimeDecompose
implicit none
integer, parameter :: huge = selected_int_kind(18)
! => integer(8) ... more fails on my 32 bit machine with gfortran(gcc) 4.3.2
contains
subroutine find_factors(n, d)
integer(huge), intent(in) :: n
integer, dimension(:), intent(out) :: d
integer(huge) :: div, next, rest
integer :: i
i = 1
div = 2; next = 3; rest = n
do while ( rest /= 1 )
do while ( mod(rest, div) == 0 )
d(i) = div
i = i + 1
rest = rest / div
end do
div = next
next = next + 2
end do
end subroutine find_factors
end module PrimeDecompose

View file

@ -0,0 +1,17 @@
program Primes
use PrimeDecompose
implicit none
integer, dimension(100) :: outprimes
integer i
outprimes = 0
call find_factors(12345649494449_huge, outprimes)
do i = 1, 100
if ( outprimes(i) == 0 ) exit
print *, outprimes(i)
end do
end program Primes

View file

@ -0,0 +1 @@
println[factor[2^508-1]]

View file

@ -0,0 +1,2 @@
FactorsInt(2^67-1);
# [ 193707721, 761838257287 ]

View file

@ -0,0 +1,2 @@
FactInt(2^67-1);
# [ [ 193707721, 761838257287 ], [ ] ]

View file

@ -0,0 +1,39 @@
package main
import (
"fmt"
"math/big"
)
var (
ZERO = big.NewInt(0)
ONE = big.NewInt(1)
)
func Primes(n *big.Int) []*big.Int {
res := []*big.Int{}
mod, div := new(big.Int), new(big.Int)
for i := big.NewInt(2); i.Cmp(n) != 1; {
div.DivMod(n, i, mod)
for mod.Cmp(ZERO) == 0 {
res = append(res, new(big.Int).Set(i))
n.Set(div)
div.DivMod(n, i, mod)
}
i.Add(i, ONE)
}
return res
}
func main() {
vals := []int64{
1 << 31,
1234567,
333333,
987653,
2 * 3 * 5 * 7 * 11 * 13 * 17,
}
for _, v := range vals {
fmt.Println(v, "->", Primes(big.NewInt(v)))
}
}

View file

@ -0,0 +1,29 @@
def factorize = { long target ->
if (target == 1) return [1L]
if (target < 4) return [1L, target]
def targetSqrt = Math.sqrt(target)
def lowfactors = (2L..targetSqrt).findAll { (target % it) == 0 }
if (lowfactors == []) return [1L, target]
def nhalf = lowfactors.size() - ((lowfactors[-1]**2 == target) ? 1 : 0)
[1] + lowfactors + (0..<nhalf).collect { target.intdiv(lowfactors[it]) }.reverse() + [target]
}
def decomposePrimes = { target ->
def factors = factorize(target) - [1]
def primeFactors = []
factors.eachWithIndex { f, i ->
if (i==0 || factors[0..<i].every {f % it != 0}) {
primeFactors << f
def pfPower = f*f
while (target % pfPower == 0) {
primeFactors << f
pfPower *= f
}
}
}
primeFactors
}

View file

@ -0,0 +1 @@
((1..30) + [97*4, 1000, 1024, 333333]).each { println ([number:it, primes:decomposePrimes(it)]) }

View file

@ -0,0 +1,2 @@
def isPrime = {factorize(it).size() == 2}
(1..60).step(2).findAll(isPrime).each { println ([number:"2**${it}-1", value:2**it-1, primes:decomposePrimes(2**it-1)]) }

View file

@ -0,0 +1,3 @@
factorize_ n | n > 1 = concat [divs n p | p <- [2..n], isPrime p]
where
divs n p = if rem n p==0 then p:divs (quot n p) p else []

View file

@ -0,0 +1,8 @@
factorize n | n > 1 = go n primesList
where
go n ds@(d:t)
| d*d > n = [n]
| r == 0 = d : go q ds
| otherwise = go n t
where
(q,r) = quotRem n d

View file

@ -0,0 +1,18 @@
procedure main()
factors := primedecomp(2^43-1) # a big int
end
procedure primedecomp(n) #: return a list of factors
local F,o,x
F := []
every writes(o,n|(x := genfactors(n))) do {
\o := "*"
/o := "="
put(F,x) # build a list of factors to satisfy the task
}
write()
return F
end
link factors

View file

@ -0,0 +1 @@
q:

View file

@ -0,0 +1,9 @@
q: 3684
2 2 3 307
_1+2^128x
340282366920938463463374607431768211455
q: _1+2^128x
3 5 17 257 641 65537 274177 6700417 67280421310721
*/ q: _1+2^128x
340282366920938463463374607431768211455

View file

@ -0,0 +1 @@
public boolean prime(BigInteger i);

View file

@ -0,0 +1,12 @@
public static List<BigInteger> primeFactorBig(BigInteger a){
List<BigInteger> ans = new LinkedList<BigInteger>();
//loop until we test the number itself or the number is 1
for (BigInteger i = BigInteger.valueOf(2); i.compareTo(a) <= 0 && !a.equals(BigInteger.ONE);
i = i.add(BigInteger.ONE)){
while (a.remainder(i).equals(BigInteger.ZERO) && prime(i)) { //if we have a prime factor
ans.add(i); //put it in the list
a = a.divide(i); //factor it out of the number
}
}
return ans;
}

View file

@ -0,0 +1,32 @@
private static final BigInteger two = BigInteger.valueOf(2);
public List<BigInteger> primeDecomp(BigInteger a) {
// impossible for values lower than 2
if (a.compareTo(two) < 0) {
return null;
}
//quickly handle even values
List<BigInteger> result = new ArrayList<BigInteger>();
while (a.and(BigInteger.ONE).equals(BigInteger.ZERO)) {
a = a.shiftRight(1);
result.add(two);
}
//left with odd values
if (!a.equals(BigInteger.ONE)) {
BigInteger b = BigInteger.valueOf(3);
while (b.compareTo(a) < 0) {
if (b.isProbablePrime(10)) {
BigInteger[] dr = a.divideAndRemainder(b);
if (dr[1].equals(BigInteger.ZERO)) {
result.add(b);
a = dr[0];
}
}
b = b.add(two);
}
result.add(b); //b will always be prime here...
}
return result;
}

View file

@ -0,0 +1,11 @@
public static List<BigInteger> primeFactorBig(BigInteger a){
List<BigInteger> ans = new LinkedList<BigInteger>();
for(BigInteger divisor = BigInteger.valueOf(2);
a.compareTo(ONE) > 0; divisor = divisor.add(ONE))
while(a.mod(divisor).equals(ZERO)){
ans.add(divisor);
a = a.divide(divisor);
}
return ans;
}

View file

@ -0,0 +1,39 @@
function run_factorize(input, output) {
var n = new BigInteger(input.value, 10);
var TWO = new BigInteger("2", 10);
var divisor = new BigInteger("3", 10);
var prod = false;
if (n.compareTo(TWO) < 0)
return;
output.value = "";
while (true) {
var qr = n.divideAndRemainder(TWO);
if (qr[1].equals(BigInteger.ZERO)) {
if (prod)
output.value += "*";
else
prod = true;
output.value += "2";
n = qr[0];
}
else
break;
}
while (!n.equals(BigInteger.ONE)) {
var qr = n.divideAndRemainder(divisor);
if (qr[1].equals(BigInteger.ZERO)) {
if (prod)
output.value += "*";
else
prod = true;
output.value += divisor;
n = qr[0];
}
else
divisor = divisor.add(TWO);
}
}

View file

@ -0,0 +1,41 @@
function run_factorize(n) {
if (n <= 3)
return [n];
var ans = [];
var done = false;
while (!done)
{
if (n%2 === 0){
ans.push(2);
n /= 2;
continue;
}
if (n%3 === 0){
ans.push(3);
n /= 3;
continue;
}
if ( n === 1)
return ans;
var sr = Math.sqrt(n);
done = true;
// try to divide the checked number by all numbers till its square root.
for (var i=6; i<=sr; i+=6){
if (n%(i-1) === 0){ // is n divisible by i-1?
ans.push( (i-1) );
n /= (i-1);
done = false;
break;
}
if (n%(i+1) === 0){ // is n divisible by i+1?
ans.push( (i+1) );
n /= (i+1);
done = false;
break;
}
}
}
ans.push( n );
return ans;
}

View file

@ -0,0 +1,5 @@
to decompose :n [:p 2]
if :p*:p > :n [output (list :n)]
if less? 0 modulo :n :p [output (decompose :n bitor 1 :p+1)]
output fput :p (decompose :n/:p :p)
end

View file

@ -0,0 +1,22 @@
function PrimeDecomposition( n )
local f = {}
if IsPrime( n ) then
f[1] = n
return f
end
local i = 2
repeat
while n % i == 0 do
f[#f+1] = i
n = n / i
end
repeat
i = i + 1
until IsPrime( i )
until n == 1
return f
end

View file

@ -0,0 +1,2 @@
function [outputPrimeDecomposition] = primedecomposition(inputValue)
outputPrimeDecomposition = factor(inputValue);

View file

@ -0,0 +1,22 @@
ERATO1(HI)
SET HI=HI\1
KILL ERATO1 ;Don't make it new - we want it to remain after the quit
NEW I,J,P
FOR I=2:1:(HI**.5)\1 DO
.FOR J=I*I:I:HI DO
..SET P(J)=1 ;$SELECT($DATA(P(J))#10:P(J)+1,1:1)
;WRITE !,"Prime numbers between 2 and ",HI,": "
FOR I=2:1:HI DO
.S:'$DATA(P(I)) ERATO1(I)=I ;WRITE $SELECT((I<3):"",1:", "),I
KILL I,J,P
QUIT
PRIMDECO(N)
;Returns its results in the string PRIMDECO
;Kill that before the first call to this recursive function
QUIT:N<=1
IF $D(PRIMDECO)=1 SET PRIMDECO="" D ERATO1(N)
SET N=N\1,I=0
FOR SET I=$O(ERATO1(I)) Q:+I<1 Q:'(N#I)
IF I>1 SET PRIMDECO=$S($L(PRIMDECO)>0:PRIMDECO_"^",1:"")_I D PRIMDECO(N/I)
;that is, if I is a factor of N, add it to the string
QUIT

View file

@ -0,0 +1 @@
FactorInteger[2016] => {{2, 5}, {3, 2}, {7, 1}}

View file

@ -0,0 +1,2 @@
supscript[x_,y_]:=If[y==1,x,Superscript[x,y]]
ShowPrimeDecomposition[input_Integer]:=Print@@{input," = ",Sequence@@Riffle[supscript@@@FactorInteger[input]," "]}

View file

@ -0,0 +1 @@
ShowPrimeDecomposition[1337]

View file

@ -0,0 +1 @@
1337 = 7 191

View file

@ -0,0 +1 @@
Table[AbsoluteTiming[ShowPrimeDecomposition[2^a-1]]//Print[#[[1]]," sec"]&,{a,50,150,10}];

View file

@ -0,0 +1,22 @@
1125899906842623 = 3 11 31 251 601 1801 4051
0.000231 sec
1152921504606846975 = 3^2 5^2 7 11 13 31 41 61 151 331 1321
0.000146 sec
1180591620717411303423 = 3 11 31 43 71 127 281 86171 122921
0.001008 sec
1208925819614629174706175 = 3 5^2 11 17 31 41 257 61681 4278255361
0.000340 sec
1237940039285380274899124223 = 3^3 7 11 19 31 73 151 331 631 23311 18837001
0.000192 sec
1267650600228229401496703205375 = 3 5^3 11 31 41 101 251 601 1801 4051 8101 268501
0.000156 sec
1298074214633706907132624082305023 = 3 11^2 23 31 89 683 881 2971 3191 201961 48912491
0.001389 sec
1329227995784915872903807060280344575 = 3^2 5^2 7 11 13 17 31 41 61 151 241 331 1321 61681 4562284561
0.000374 sec
1361129467683753853853498429727072845823 = 3 11 31 131 2731 8191 409891 7623851 145295143558111
0.024249 sec
1393796574908163946345982392040522594123775 = 3 5^2 11 29 31 41 43 71 113 127 281 86171 122921 7416361 47392381
0.009419 sec
1427247692705959881058285969449495136382746623 = 3^2 7 11 31 151 251 331 601 1801 4051 100801 10567201 1133836730401
0.007705 sec

View file

@ -0,0 +1,3 @@
(%i1) display2d: false$ /* disable rendering exponents as superscripts */
(%i2) factor(2016);
(%o2) 2^5*3^2*7

View file

@ -0,0 +1,7 @@
prime_dec(n) := apply(append, create_list(makelist(a[1], a[2]), a, ifactors(n)))$
/* or, slighlty more "functional" */
prime_dec(n) := apply(append, map(lambda([a], apply(makelist, a)), ifactors(n)))$
prime_dec(2^4*3^5*5*7^2);
/* [2, 2, 2, 2, 3, 3, 3, 3, 3, 5, 7, 7] */

View file

@ -0,0 +1,12 @@
open Big_int;;
let prime_decomposition x =
let rec inner c p =
if lt_big_int p (square_big_int c) then
[p]
else if eq_big_int (mod_big_int p c) zero_big_int then
c :: inner c (div_big_int p c)
else
inner (succ_big_int c) p
in
inner (succ_big_int (succ_big_int zero_big_int)) x;;

View file

@ -0,0 +1 @@
r = factor(120202039393)

View file

@ -0,0 +1,9 @@
pd(n)={
my(f=factor(n),v=f[,1]~);
for(i=1,#v,
while(f[i,2]--,
v=concat(v,f[i,1])
)
);
vecsort(v)
};

View file

@ -0,0 +1,41 @@
test: procedure options (main, reorder);
declare (n, i) fixed binary (31);
get list (n);
put edit ( n, '[' ) (x(1), a);
restart:
if is_prime(n) then
do;
put edit (trim(n), ']' ) (x(1), a);
stop;
end;
do i = n/2 to 2 by -1;
if is_prime(i) then
if (mod(n, i) = 0) then
do;
put edit ( trim(i) ) (x(1), a);
n = n / i;
go to restart;
end;
end;
put edit ( ' ]' ) (a);
is_prime: procedure (n) options (reorder) returns (bit(1));
declare n fixed binary (31);
declare i fixed binary (31);
if n < 2 then return ('0'b);
if n = 2 then return ('1'b);
if mod(n, 2) = 0 then return ('0'b);
do i = 3 to sqrt(n) by 2;
if mod(n, i) = 0 then return ('0'b);
end;
return ('1'b);
end is_prime;
end test;

View file

@ -0,0 +1,38 @@
Program PrimeDecomposition(output);
type
DynArray = array of integer;
procedure findFactors(n: Int64; var d: DynArray);
var
divisor, next, rest: Int64;
i: integer;
begin
i := 0;
divisor := 2;
next := 3;
rest := n;
while (rest <> 1) do
begin
while (rest mod divisor = 0) do
begin
setlength(d, i+1);
d[i] := divisor;
inc(i);
rest := rest div divisor;
end;
divisor := next;
next := next + 2;
end;
end;
var
factors: DynArray;
j: integer;
begin
setlength(factors, 1);
findFactors(1023*1024, factors);
for j := low(factors) to high(factors) do
writeln (factors[j]);
end.

View file

@ -0,0 +1,22 @@
constant @primes = 2, 3, 5, -> $n is copy {
repeat { $n += 2 } until $n %% none @primes ... { $_ * $_ >= $n }
$n;
} ... *;
sub factors(Int $remainder is copy) {
return 1 if $remainder <= 1;
gather for @primes -> $factor {
if $factor * $factor > $remainder {
take $remainder if $remainder > 1;
last;
}
# How many times can we divide by this prime?
while $remainder %% $factor {
take $factor;
last if ($remainder div= $factor) === 1;
}
}
}
say factors 536870911;

View file

@ -0,0 +1,9 @@
sub prime_factors {
my ($n, $d, @out) = (shift, 1);
while ($n > 1 && $d++) {
$n /= $d, push @out, $d until $n % $d;
}
@out
}
print "@{[prime_factors(1001)]}\n";

View file

@ -0,0 +1,10 @@
(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) ) ) )
(factor 1361129467683753853853498429727072845823)

View file

@ -0,0 +1,37 @@
prime_decomp(N, L) :-
SN is sqrt(N),
prime_decomp_1(N, SN, 2, [], L).
prime_decomp_1(1, _, _, L, L) :- !.
% Special case for 2, increment 1
prime_decomp_1(N, SN, D, L, LF) :-
( 0 is N mod D ->
Q is N / D,
SQ is sqrt(Q),
prime_decomp_1(Q, SQ, D, [D |L], LF)
;
D1 is D+1,
( D1 > SN ->
LF = [N |L]
;
prime_decomp_2(N, SN, D1, L, LF)
)
).
% General case, increment 2
prime_decomp_2(1, _, _, L, L) :- !.
prime_decomp_2(N, SN, D, L, LF) :-
( 0 is N mod D ->
Q is N / D,
SQ is sqrt(Q),
prime_decomp_2(Q, SQ, D, [D |L], LF);
D1 is D+2,
( D1 > SN ->
LF = [N |L]
;
prime_decomp_2(N, SN, D1, L, LF)
)
).

View file

@ -0,0 +1,11 @@
?- time(prime_decomp(9007199254740991, L)).
% 138,882 inferences, 0.344 CPU in 0.357 seconds (96% CPU, 404020 Lips)
L = [20394401,69431,6361].
?- time(prime_decomp(576460752303423487, L)).
% 2,684,734 inferences, 0.672 CPU in 0.671 seconds (100% CPU, 3995883 Lips)
L = [3203431780337,179951].
?- time(prime_decomp(1361129467683753853853498429727072845823, L)).
% 18,080,807 inferences, 7.953 CPU in 7.973 seconds (100% CPU, 2273422 Lips)
L = [145295143558111,7623851,409891,8191,2731,131,31,11,3].

View file

@ -0,0 +1,6 @@
factor n = factor 2 n with
factor k n = k : factor k (n div k) if n mod k == 0;
= if n>1 then [n] else [] if k*k>n;
= factor (k+1) n if k==2;
= factor (k+2) n otherwise;
end;

View file

@ -0,0 +1,34 @@
CompilerIf #PB_Compiler_Debugger
CompilerError "Turn off the debugger if you want reasonable speed in this example."
CompilerEndIf
Define.q
Procedure Factor(Number, List Factors())
Protected I = 3
While Number % 2 = 0
AddElement(Factors())
Factors() = 2
Number / 2
Wend
Protected Max = Number
While I <= Max And Number > 1
While Number % I = 0
AddElement(Factors())
Factors() = I
Number/I
Wend
I + 2
Wend
EndProcedure
Number = 9007199254740991
NewList Factors()
time = ElapsedMilliseconds()
Factor(Number, Factors())
time = ElapsedMilliseconds()-time
S.s = "Factored " + Str(Number) + " in " + StrD(time/1000, 2) + " seconds."
ForEach Factors()
S + #CRLF$ + Str(Factors())
Next
MessageRequester("", S)

View file

@ -0,0 +1,47 @@
import sys
def is_prime(n):
return zip((True, False), decompose(n))[-1][0]
class IsPrimeCached(dict):
def __missing__(self, n):
r = is_prime(n)
self[n] = r
return r
is_prime_cached = IsPrimeCached()
def primes():
yield 2
n = 3
while n < sys.maxint - 2:
yield n
n += 2
while n < sys.maxint - 2 and not is_prime_cached[n]:
n += 2
def decompose(n):
for p in primes():
if p*p > n: break
while n % p == 0:
yield p
n /=p
if n > 1:
yield n
if __name__ == '__main__':
# Example: calculate factors of Mersenne numbers to M59 #
import time
for m in primes():
p = 2 ** m - 1
print( "2**{0:d}-1 = {0:d}, with factors:".format(m, p) )
start = time.time()
for factor in decompose(p):
print factor,
sys.stdout.flush()
print( "=> {0:.2f}s".format( time.time()-start ) )
if m >= 59:
break

View file

@ -0,0 +1,18 @@
primelist = [2,3]
def is_prime(n):
for y in primes():
if not n % y: return False
if n > y * y: return True
def primes():
for n in primelist: yield n
n = primelist[-1] + 2
while True:
n += 2
for x in primelist:
if not n % x: break
if x * x > n:
primelist.append(n)
yield n
break

View file

@ -0,0 +1,21 @@
def fac(n):
step = lambda x: 1 + x*4 - (x/2)*2
maxq = long(math.floor(math.sqrt(n)))
d = 1
q = n % 2 == 0 and 2 or 3
while q <= maxq and n % q != 0:
q = step(d)
d += 1
res = []
if q <= maxq:
res.extend(fac(n//q))
res.extend(fac(q))
else: res=[n]
return res
if __name__ == '__main__':
import time
start = time.time()
tocalc = 2**59-1
print "%s = %s" % (tocalc, fac(tocalc))
print "Needed %ss" % (time.time() - start)

View file

@ -0,0 +1,15 @@
findfactors <- function(n) {
d <- c()
div <- 2; nxt <- 3; rest <- n
while( rest != 1 ) {
while( rest%%div == 0 ) {
d <- c(d, div)
rest <- floor(rest / div)
}
div <- nxt
nxt <- nxt + 2
}
d
}
print(findfactors(1005025))

View file

@ -0,0 +1,32 @@
/*REXX program fins the prime factors of a (or some) positive integer(s)*/
numeric digits 100 /*bump up precision of the nums. */
parse arg low high . /*get the argument(s). */
if low=='' then low=1 /*no LOW? Then make one up. */
if high=='' then high=low /*no HIGH? Then make one up. */
w=length(high) /*get max width for pretty tell. */
do n=low to high /*process single number | a range*/
say right(n,w) 'prime factors =' factr(n)
end /*n*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────FACTR subroutine────────────────────*/
factr: procedure; parse arg x 1 z,,list /*sets X&Z to arg1, LIST to null*/
if x <1 then return '' /*Too small? Then return null.*/
if x==1 then return 1 /*special case for unity. */
do j=2 to 5; if j\==4 then call buildF; end /*fast builds for list.*/
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 /*num. reduced to a small number?*/
if j*j>x then leave /*are we higher than the √ of X ?*/
call buildF /*add a prime factor to list (J).*/
end /*y*/
if z==1 then return strip(list) /*if residual=unity, don't append*/
return strip(list z) /*return list, append residual. */
/*──────────────────────────────────BUILDF subroutine───────────────────*/
buildF: do forever /*keep dividing until it hurts. */
if z//j\==0 then return /*can't divide any more? */
list=list j /*add number to the list (J). */
z=z%j /*do an integer divide. */
end /*forever*/

View file

@ -0,0 +1,4 @@
irb(main):001:0> require 'mathn'
=> true
irb(main):002:0> 2131447995319.prime_division
=> [[701, 1], [1123, 2], [2411, 1]]

View file

@ -0,0 +1,4 @@
irb(main):001:0> require 'prime'
=> true
irb(main):003:0> 2543821448263974486045199.prime_division
=> [[701, 1], [1123, 2], [2411, 1], [1092461, 2]]

View file

@ -0,0 +1,13 @@
# Get prime decomposition of integer _i_.
# This routine is terribly inefficient, but elegance rules.
def prime_factors(i)
v = (2..i-1).detect{|j| i % j == 0}
v ? ([v] + prime_factors(i/v)) : [i]
end
# Example: Decompose all possible Mersenne primes up to 2**31-1.
# This may take several minutes to show that 2**31-1 is prime.
(2..31).each do |i|
factors = prime_factors(2**i-1)
puts "2**#{i}-1 = #{2**i-1} = #{factors.join(' * ')}"
end

View file

@ -0,0 +1,32 @@
# Get prime decomposition of integer _i_.
# This routine is more efficient than prime_factors,
# and quite similar to Integer#prime_division of MRI 1.9.
def prime_factors_faster(i)
factors = []
check = proc do |p|
while(q, r = i.divmod(p)
r.zero?)
factors << p
i = q
end
end
check[2]
check[3]
p = 5
while p * p <= i
check[p]
p += 2
check[p]
p += 4 # skip multiples of 2 and 3
end
factors << i if i > 1
factors
end
# Example: Decompose all possible Mersenne primes up to 2**70-1.
# This may take several minutes to show that 2**61-1 is prime,
# but 2**62-1 and 2**67-1 are not prime.
(2..70).each do |i|
factors = prime_factors_faster(2**i-1)
puts "2**#{i}-1 = #{2**i-1} = #{factors.join(' * ')}"
end

View file

@ -0,0 +1,10 @@
require 'benchmark'
require 'mathn'
Benchmark.bm(24) do |x|
[2**25 - 6, 2**35 - 7].each do |i|
puts "#{i} = #{prime_factors_faster(i).join(' * ')}"
x.report(" prime_factors") { prime_factors(i) }
x.report(" prime_factors_faster") { prime_factors_faster(i) }
x.report(" Integer#prime_division") { i.prime_division }
end
end

View file

@ -0,0 +1,33 @@
class PrimeFactors(n: BigInt) extends Iterator[BigInt] {
val zero = BigInt(0)
val one = BigInt(1)
val two = BigInt(2)
def isPrime(n: BigInt) = n.isProbablePrime(10)
var currentN = n
var prime = two
def nextPrime =
if (prime == two) {
prime += one
} else {
prime += two
while (!isPrime(prime)) {
prime += two
if (prime * prime > currentN)
prime = currentN
}
}
def next = {
if (!hasNext)
throw new NoSuchElementException("next on empty iterator")
while(currentN % prime != zero) {
nextPrime
}
currentN /= prime
prime
}
def hasNext = currentN != one && currentN > zero
}

View file

@ -0,0 +1,25 @@
class PrimeFactors[N](n: N)(implicit num: Integral[N]) extends Iterator[N] {
import num._
val two = one + one
var currentN = n
var divisor = two
def next = {
if (!hasNext)
throw new NoSuchElementException("next on empty iterator")
while(currentN % divisor != zero) {
if (divisor == two)
divisor += one
else
divisor += two
if (divisor * divisor > currentN)
divisor = currentN
}
currentN /= divisor
divisor
}
def hasNext = currentN != one && currentN > zero
}

View file

@ -0,0 +1,18 @@
import scala.math.BigInt
def primeStream(s: Stream[Int]): Stream[Int] = {
Stream.cons(s.head, primeStream(s.tail filter { _ % s.head != 0 }))
}
// An infinite stream of primes
val primes = primeStream(Stream.from(2))
def primeFactor(n:BigInt) = { primes.takeWhile(_ <= n).find(i => n % i == 0) }
def decompose( n : BigInt ) : List[BigInt] = {
primeFactor(n) match {
case Some(a) => a.toInt :: decompose(n/a)
case None => Nil
}
}

View file

@ -0,0 +1,11 @@
// A test
decompose(423) // Results: List(3,3,47)
decompose(423).product // Results: 423
// A BigInt test
decompose(BigInt("2535301200456458802993406410752"))
// Results: a list of (2)s
decompose(BigInt("2535301200456458802993406410752")).length
// Results: 101
decompose(BigInt("2535301200456458802993406410752")).product
// Results: 2535301200456458802993406410752

View file

@ -0,0 +1,11 @@
(define (factor number)
(define (*factor divisor number)
(if (> (* divisor divisor) number)
(list number)
(if (= (modulo number divisor) 0)
(cons divisor (*factor divisor (/ number divisor)))
(*factor (+ divisor 1) number))))
(*factor 2 number))
(display (factor 111111111111))
(newline)

View file

@ -0,0 +1,18 @@
const func array integer: factorise (in var integer: number) is func
result
var array integer: result is 0 times 0;
local
var integer: checker is 2;
begin
while checker * checker <= number do
if number rem checker = 0 then
result &:= [](checker);
number := number div checker;
else
incr(checker);
end if;
end while;
if number <> 1 then
result &:= [](number);
end if;
end func;

View file

@ -0,0 +1,15 @@
n@(Integer traits) primesDo: block
"Decomposes the Integer into primes, applying the block to each (in increasing
order)."
[| div next remaining |
div: 2.
next: 3.
remaining: n.
[[(remaining \\ div) isZero]
whileTrue:
[block applyTo: {div}.
remaining: remaining // div].
remaining = 1] whileFalse:
[div: next.
next: next + 2] "Just look at the next odd integer."
].

View file

@ -0,0 +1,14 @@
Integer extend [
primesDo: aBlock [
| div next rest |
div := 2. next := 3.
rest := self.
[ [ rest \\ div == 0 ]
whileTrue: [
aBlock value: div.
rest := rest // div ].
rest = 1] whileFalse: [
div := next. next := next + 2 ]
]
]
123456 primesDo: [ :each | each printNl ]

View file

@ -0,0 +1,16 @@
@(next :args)
@(do
(defun factor (n)
(if (> n 1)
(for ((max-d (sqrt n))
(d 2))
(t)
((set d (if (evenp d) (+ d 1) (+ d 2))))
(cond ((> d max-d) (return (list n)))
((zerop (mod n d))
(return (cons d (factor (trunc n d))))))))))
@{num /[0-9]+/}
@(bind factors @(factor (int-str num 10)))
@(output)
@num -> {@(rep)@factors, @(last)@factors@(end)}
@(end)

View file

@ -0,0 +1,93 @@
namespace eval primes {}
proc primes::reset {} {
variable list [list]
variable current_index end
}
namespace eval primes {reset}
proc primes::restart {} {
variable list
variable current_index
if {[llength $list] > 0} {
set current_index 0
}
}
proc primes::is_prime {candidate} {
variable list
if {$candidate in $list} {return true}
foreach prime $list {
if {$candidate % $prime == 0} {
return false
}
if {$prime * $prime > $candidate} {
return true
}
}
while true {
set largest [get_next_prime]
if {$largest * $largest >= $candidate} {
return [is_prime $candidate]
}
}
}
proc primes::get_next_prime {} {
variable list
variable current_index
if {$current_index ne "end"} {
set p [lindex $list $current_index]
if {[incr current_index] == [llength $list]} {
set current_index end
}
return $p
}
switch -exact -- [llength $list] {
0 {set candidate 2}
1 {set candidate 3}
default {
set candidate [lindex $list end]
while true {
incr candidate 2
if {[is_prime $candidate]} break
}
}
}
lappend list $candidate
return $candidate
}
# return the prime factors of a number in a dictionary.
# The keys will be the factors, the value will be the number
# of times the factor divides the given number
#
# example: 120 = 2**3 * 3 * 5, so
# [primes::factors 120] returns 2 3 3 1 5 1
# so: set prod 1
# dict for {p e} [primes::factors 120] {
# set prod [expr {$prod * $p**$e}]
# }
# expr {$prod == 120} ;# ==> true
#
proc primes::factors {num} {
restart
set factors [dict create]
for {set i [get_next_prime]} {$i <= $num} {} {
if {$num % $i == 0} {
dict incr factors $i
set num [expr {$num / $i}]
continue
} elseif {$i*$i > $num} {
dict incr factors $num
break
} else {
set i [get_next_prime]
}
}
return $factors
}

View file

@ -0,0 +1,8 @@
primes::reset
foreach m {2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59} {
set n [expr {2**$m - 1}]
catch {time {set f [dict create {*}[primes::factors $n]]} 1} tm
set primes [list]
dict for {p e} $f {lappend primes {*}[lrepeat $e $p]}
puts [format "2**%02d-1 = %-18s = %-22s => %s" $m $n [join $primes *] $tm]
}

View file

@ -0,0 +1,10 @@
[prime-decomposition
[inner [c p] let
[c c * p >]
[p unit]
[ [p c % zero?]
[c c p c / inner cons]
[c 1 + p inner]
ifte]
ifte].
2 swap inner].

View file

@ -0,0 +1,10 @@
[prime-decomposition
[inner
[dup * <]
[pop unit]
[ [% zero?]
[ [p c : [c p c / c]] view i inner cons]
[succ inner]
ifte]
ifte].
2 inner].

View file

@ -0,0 +1 @@
|1221 prime-decomposition puts

View file

@ -0,0 +1,73 @@
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/numbers">
<html>
<body>
<ul>
<xsl:apply-templates />
</ul>
</body>
</html>
</xsl:template>
<xsl:template match="number">
<li>
Number:
<xsl:apply-templates mode="value" />
Factors:
<xsl:apply-templates mode="factors" />
</li>
</xsl:template>
<xsl:template match="value" mode="value">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="value" mode="factors">
<xsl:call-template name="generate">
<xsl:with-param name="number" select="number(current())" />
<xsl:with-param name="candidate" select="number(2)" />
</xsl:call-template>
</xsl:template>
<xsl:template name="generate">
<xsl:param name="number" />
<xsl:param name="candidate" />
<xsl:choose>
<!-- 1 is no prime and does not have any factors -->
<xsl:when test="$number = 1"></xsl:when>
<!-- if the candidate is larger than the sqrt of the number, it's prime and the last factor -->
<xsl:when test="$candidate * $candidate &gt; $number">
<xsl:value-of select="$number" />
</xsl:when>
<!-- if the number is factored by the candidate, add the factor and try again with the same factor -->
<xsl:when test="$number mod $candidate = 0">
<xsl:value-of select="$candidate" />
<xsl:text> </xsl:text>
<xsl:call-template name="generate">
<xsl:with-param name="number" select="$number div $candidate" />
<xsl:with-param name="candidate" select="$candidate" />
</xsl:call-template>
</xsl:when>
<!-- else try again with the next factor -->
<xsl:otherwise>
<!-- increment by 2 to save stack depth -->
<xsl:choose>
<xsl:when test="$candidate = 2">
<xsl:call-template name="generate">
<xsl:with-param name="number" select="$number" />
<xsl:with-param name="candidate" select="$candidate + 1" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="generate">
<xsl:with-param name="number" select="$number" />
<xsl:with-param name="candidate" select="$candidate + 2" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>

View file

@ -0,0 +1,8 @@
<numbers>
<number><value>1</value></number>
<number><value>2</value></number>
<number><value>4</value></number>
<number><value>8</value></number>
<number><value>9</value></number>
<number><value>255</value></number>
</numbers>

View file

@ -0,0 +1,43 @@
<html>
<body>
<ul>
<li>
Number:
1
Factors:
</li>
<li>
Number:
2
Factors:
2</li>
<li>
Number:
4
Factors:
2 2</li>
<li>
Number:
8
Factors:
2 2 2</li>
<li>
Number:
9
Factors:
3 3</li>
<li>
Number:
255
Factors:
3 5 17</li>
</ul>
</body>
</html>