Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
category:
- Arbitrary precision
from: http://rosettacode.org/wiki/Prime_decomposition
note: Prime Numbers

View file

@ -0,0 +1,31 @@
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}
;Task:
Write a function which returns an [[Arrays|array]] or [[Collections|collection]] which contains the prime decomposition of a given number &nbsp; <big><big><math>n</math></big></big> &nbsp; greater than &nbsp; '''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).
;Related tasks:
* &nbsp; [[count in factors]]
* &nbsp; [[factors of an integer]]
* &nbsp; [[Sieve of Eratosthenes]]
* &nbsp; [[primality by trial division]]
* &nbsp; [[factors of a Mersenne number]]
* &nbsp; [[trial factoring of a Mersenne number]]
* &nbsp; [[partition an integer X into N primes]]
* &nbsp; [[sequence of primes by Trial Division]]
<br><br>

View file

@ -0,0 +1,22 @@
F decompose(BigInt number)
[BigInt] result
V n = number
BigInt i = 2
L n % i == 0
result.append(i)
n I/= i
i = 3
L n >= i * i
L n % i == 0
result.append(i)
n I/= i
i += 2
I n != 1
result.append(n)
R result
L(i) 2..9
print(decompose(i))
print(decompose(1023 * 1024))
print(decompose(2 * 3 * 5 * 7 * 11 * 11 * 13 * 17))
print(decompose(BigInt(16860167264933) * 179951))

View file

@ -0,0 +1,76 @@
PRIMEDE CSECT
USING PRIMEDE,R13
B 80(R15) skip savearea
DC 17F'0' savearea
DC CL8'PRIMEDE'
STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15 end prolog
LA R2,0
LA R3,1023
LA R4,1024
MR R2,R4
ST R3,N n=1023*1024
LA R5,WBUFFER
LA R6,0
L R1,N n
XDECO R1,0(R5)
LA R5,12(R5)
MVC 0(3,R5),=C' : '
LA R5,3(R5)
LA R0,2
ST R0,I i=2
WHILE1 EQU * do while(i<=n/2)
L R2,N
SRA R2,1
L R4,I
CR R4,R2 i<=n/2
BH EWHILE1
WHILE2 EQU * do while(n//i=0)
L R3,N
LA R2,0
D R2,I
LTR R2,R2 n//i=0
BNZ EWHILE2
ST R3,N n=n/i
ST R3,M m=n
L R1,I i
XDECO R1,WDECO
MVC 0(5,R5),WDECO+7
LA R5,5(R5)
MVI OK,X'01' ok
B WHILE2
EWHILE2 EQU *
L R4,I
CH R4,=H'2' if i=2 then
BNE NE2
LA R0,3
ST R0,I i=3
B EIFNE2
NE2 L R2,I else
LA R2,2(R2)
ST R2,I i=i+2
EIFNE2 B WHILE1
EWHILE1 EQU *
CLI OK,X'01' if ^ok then
BE NOTPRIME
MVC 0(7,R5),=C'[prime]'
LA R5,7(R5)
B EPRIME
NOTPRIME L R1,M m
XDECO R1,WDECO
MVC 0(5,R5),WDECO+7
EPRIME XPRNT WBUFFER,80 put
L R13,4(0,R13) epilog
LM R14,R12,12(R13)
XR R15,R15
BR R14
N DS F
I DS F
M DS F
OK DC X'00'
WBUFFER DC CL80' '
WDECO DS CL16
YREGS
END PRIMEDE

View file

@ -0,0 +1,224 @@
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program primeDecomp64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBFACT, 100
/*******************************************/
/* Structures */
/********************************************/
/* structurea area factors */
.struct 0
fac_value: // factor
.struct fac_value + 8
fac_number: // number of identical factors
.struct fac_number + 8
fac_end:
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessNotPrime: .asciz "Not prime.\n"
szMessPrime: .asciz "Prime\n"
szCarriageReturn: .asciz "\n"
szSpaces: .asciz " "
szMessNumber: .asciz " The factors of @ are :\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
sZoneConv: .skip 32
.align 4
tbZoneDecom: .skip fac_end * NBFACT
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // program start
ldr x0,qAdrszMessStartPgm // display start message
bl affichageMess
ldr x20,qVal
//mov x20,17
mov x0,x20
ldr x1,qAdrtbZoneDecom
bl decompFact // decomposition
cmp x0,#0
beq 1f
mov x2,x0
mov x0,x20
ldr x1,qAdrtbZoneDecom
bl displayFactors // display factors
b 2f
1:
ldr x0,qAdrszMessPrime // prime
bl affichageMess
2:
ldr x0,qAdrszMessEndPgm // display end message
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrszMessStartPgm: .quad szMessStartPgm
qAdrszMessEndPgm: .quad szMessEndPgm
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessNotPrime: .quad szMessNotPrime
qAdrszMessPrime: .quad szMessPrime
qAdrtbZoneDecom: .quad tbZoneDecom
//qVal: .quad 2 <<31
qVal: .quad 1047552 // test not prime
//qVal: .quad 1429671721 // test not prime (37811 * 37811)
/******************************************************************/
/* prime decomposition */
/******************************************************************/
/* x0 contains the number */
/* x1 contains address factors array */
/* REMARK no save register x9-x19 */
decompFact:
stp x1,lr,[sp,-16]! // save registers
mov x12,x0 // save number
bl isPrime // prime ?
cbnz x0,12f // yes -> no decomposition
mov x19,fac_end // element area size
mov x18,0 // raz indice
mov x16,0 // prev divisor
mov x17,0 // number of identical divisors
mov x13,2 // first divisor
2:
cmp x12,1
beq 10f
udiv x14,x12,x13 // division
msub x15,x14,x13,x12 // remainder = x12 -(x13*x14)
cbnz x15,5f // if remainder <> zero x13 not divisor
mov x12,x14 // quotient -> new dividende
cmp x13,x16 // same divisor ?
beq 4f // yes
cbz x16,3f // yes it is first divisor ?
madd x11,x18,x19,x1 // no -> store prev divisor in the area
str x16,[x11,fac_value]
str x17,[x11,fac_number] // and store number of same factor
add x18,x18,1 // increment indice
mov x17,0 // raz number of same factor
3:
mov x16,x13 // save new divisor
4:
add x17,x17,1 // increment number of same factor
mov x0,x12 // the new dividende is prime ?
bl isPrime
cbnz x0,10f // yes
b 2b // else loop
5: // divisor is not a factor
cmp x13,2 // begin ?
cinc x13,x13,ne // if divisor <> 2 add 1
add x13,x13,1
b 2b // and loop
10: // new dividende is prime
cmp x16,x12 // divisor = dividende ?
cinc x17,x17,eq //add 1 if last dividende = diviseur
madd x11,x18,x19,x1
str x16,[x11,fac_value] // store divisor in area
str x17,[x11,fac_number] // and store number
add x18,x18,1 // increment indice
cmp x16,x12 //store last dividende if <> diviseur
beq 11f
madd x11,x18,x19,x1
str x12,[x11,fac_value] // sinon stockage dans la table
mov x17,1
str x17,[x11,fac_number] // store 1 in number
add x18,x18,1
11:
mov x0,x18 // return nb factors
b 100f
12:
mov x0,#0 // number is prime
b 100f
100:
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
/******************************************************************/
/* prime decomposition */
/******************************************************************/
/* x0 contains the number */
/* x1 contains address factors array */
/* x2 number of factors */
displayFactors:
stp x1,lr,[sp,-16]! // save registres
mov x19,fac_end // element area size
mov x13,x1 // save area address
ldr x1,qAdrsZoneConv // load zone conversion address
bl conversion10
ldr x0,qAdrszMessNumber
bl strInsertAtCharInc // insert result at Second @ character
bl affichageMess
mov x9,0 // indice
1:
madd x10,x9,x19,x13 // compute address area element
ldr x0,[x10,fac_value]
ldr x12,[x10,fac_number]
bl conversion10 // decimal conversion
2:
mov x0,x1
bl affichageMess
ldr x0,qAdrszSpaces
bl affichageMess
subs x12,x12,#1
bgt 2b
add x9,x9,1
cmp x9,x2
blt 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
qAdrsZoneConv: .quad sZoneConv
qAdrszSpaces: .quad szSpaces
qAdrszMessNumber: .quad szMessNumber
/******************************************************************/
/* test if number is prime */
/******************************************************************/
/* x0 contains the number */
/* x0 return 1 if prime else return 0 */
isPrime:
stp x1,lr,[sp,-16]! // save registers
cmp x0,1 // <= 1 ?
ble 98f
cmp x0,3 // 2 and 3 prime
ble 97f
tst x0,1 // even ?
beq 98f
mov x9,3 // first divisor
1:
udiv x11,x0,x9
msub x10,x11,x9,x0 // compute remainder
cbz x10,98f // end if zero
add x9,x9,#2 // increment divisor
cmp x9,x11 // divisors<=quotient ?
ble 1b // loop
97:
mov x0,1 // return prime
b 100f
98:
mov x0,0 // not prime
b 100f
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

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,52 @@
BEGIN
INTEGER I, K, NFOUND;
INTEGER ARRAY FACTORS[1:16];
COMMENT - RETURN P MOD Q;
INTEGER FUNCTION MOD (P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
COMMENT
FIND THE PRIME FACTORS OF N AND STORE IN THE EXTERNAL
ARRAY "FACTORS", RETURNING THE NUMBER FOUND. IF N IS
PRIME, IT WILL BE STORED AS THE FIRST AND ONLY FACTOR;
INTEGER FUNCTION PRIMEFACTORS(N);
INTEGER N;
BEGIN
INTEGER P, COUNT;
P := 2;
COUNT := 1;
WHILE N >= P * P DO
BEGIN
IF MOD(N, P) = 0 THEN
BEGIN
FACTORS[COUNT] := P;
COUNT := COUNT + 1;
N := N / P;
END
ELSE
P := P + 1;
END;
FACTORS[COUNT] := N;
PRIMEFACTORS := COUNT;
END;
COMMENT -- EXERCISE THE ROUTINE;
FOR I := 77 STEP 2 UNTIL 99 DO
BEGIN
WRITE(I,":");
NFOUND := PRIMEFACTORS(I);
COMMENT - PRINT OUT THE FACTORS THAT WERE FOUND;
FOR K := 1 STEP 1 UNTIL NFOUND DO
BEGIN
WRITEON(FACTORS[K]);
END;
END;
END

View file

@ -0,0 +1,38 @@
begin % find the prime decompositionmtion of some integers %
% increments n and returns the new value %
integer procedure inc ( integer value result n ) ; begin n := n + 1; n end;
% divides n by d and returns the result %
integer procedure over ( integer value result n
; integer value d
) ; begin n := n div d; n end;
% sets the elements of f to the prime factors of n %
% the bounds of f should be 0 :: x where x is large enough to hold %
% all the factors, f( 0 ) will contain 6he number of factors %
procedure decompose ( integer value n; integer array f ( * ) ) ;
begin
integer d, v;
f( 0 ) := 0;
v := abs n;
if v > 0 and v rem 2 = 0 then begin
f( inc( f( 0 ) ) ) := 2;
while over( v, 2 ) > 0 and v rem 2 = 0 do f( inc( f( 0 ) ) ) := 2;
end if_2_divides_v ;
d := 3;
while d * d <= v do begin
if v rem d = 0 then begin
f( inc( f( 0 ) ) ) := d;
while over( v, d ) > 0 and v rem d = 0 do f( inc( f( 0 ) ) ) := d;
end if_d_divides_v ;
d := d + 2
end while_d_squared_le_v ;
if v > 1 then f( inc( f( 0 ) ) ) := v
end factorise ;
% some test cases %
for n := 0, 1, 7, 31, 127, 2047, 8191, 131071, 524287, 2520, 32767, 8855, 441421750 do begin
integer array f( 0 :: 20 );
decompose( n, f );
write( s_w := 0, n, ": " );
for fPos := 1 until f( 0 ) do writeon( i_w := 1, s_w := 0, " ", f( fPos ) );
end for_n ;
end.

View file

@ -0,0 +1,35 @@
REM Prime decomposition
DIM Facs(14)
REM -(2^15) has most prime factors (15 twos) than other 16-bit signed integer.
PRINT "Enter a number";
INPUT N
GOSUB CalcFacs:
FacsCntM1 = FacsCnt - 1
FOR I = 0 TO FacsCntM1
PRINT Facs(I);
NEXT I
PRINT
END
CalcFacs:
N = ABS(N)
FacsCnt = 0
IF N >= 2 THEN
I = 2
SqrI = I * I
WHILE SqrI <= N
NModI = N MOD I
IF NModI = 0 THEN
N = N / I
Facs(FacsCnt) = I
FacsCnt = FacsCnt + 1
I = 2
ELSE
I = I + 1
ENDIF
SqrI = I * I
WEND
Facs(FacsCnt) = N
FacsCnt = FacsCnt + 1
ENDIF
RETURN

View file

@ -0,0 +1,15 @@
# Usage: awk -f primefac.awk
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,15 @@
generic
type Number is private;
Zero : Number;
One : Number;
Two : Number;
with function "+" (X, Y : Number) return Number 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;
function Is_Prime (N : Number) return Boolean;
end Prime_Numbers;

View file

@ -0,0 +1,31 @@
package body Prime_Numbers is
-- auxiliary (internal) functions
function First_Factor (N : Number; Start : Number) return Number is
K : Number := Start;
begin
while ((N mod K) /= Zero) and then (N > (K*K)) loop
K := K + One;
end loop;
if (N mod K) = Zero then
return K;
else
return N;
end if;
end First_Factor;
function Decompose (N : Number; Start : Number) return Number_List is
F: Number := First_Factor(N, Start);
M: Number := N / F;
begin
if M = One then -- F is the last factor
return (1 => F);
else
return F & Decompose(M, Start);
end if;
end Decompose;
-- functions visible from the outside
function Decompose (N : Number) return Number_List is (Decompose(N, Two));
function Is_Prime (N : Number) return Boolean is
(N > One and then First_Factor(N, Two)=N);
end Prime_Numbers;

View file

@ -0,0 +1,18 @@
with Prime_Numbers, Ada.Text_IO;
procedure Test_Prime is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
procedure Put (List : Number_List) is
begin
for Index in List'Range loop
Ada.Text_IO.Put (Positive'Image (List (Index)));
end loop;
end Put;
begin
Put (Decompose (12));
end Test_Prime;

View file

@ -0,0 +1,13 @@
9040 PF(0) = 0 : SC = 0
9050 FOR CA = 2 TO INT( SQR(I))
9060 IF I = 1 THEN RETURN
9070 IF INT(I / CA) * CA = I THEN GOSUB 9200 : GOTO 9060
9080 CA = CA + SC : SC = 1
9090 NEXT CA
9100 IF I = 1 THEN RETURN
9110 CA = I
9200 PF(0) = PF(0) + 1
9210 PF(PF(0)) = CA
9220 I = I / CA
9230 RETURN

View file

@ -0,0 +1,9 @@
decompose: function [num][
facts: to [:string] factors.prime num
print [
pad.right (to :string num) ++ " = " ++ join.with:" x " facts 30
"{"++ (join.with:", " unique facts) ++ "}"
]
]
loop 2..40 => decompose

View file

@ -0,0 +1,17 @@
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)
return, % f "`n" next
}
f++
}
}

View file

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

View file

@ -0,0 +1,5 @@
num := 8388607, output := ""
for i, p in prime_numbers(num)
output .= p " * "
MsgBox % num " = " Trim(output, " * ")
return

View file

@ -0,0 +1,20 @@
Factor { 𝕊n:
# Prime sieve
primes 0
Sieve { p 𝕊 ab:
p()b lb-a
E {(((𝕩|-a)+𝕩×))l} # Indices of multiples of 𝕩
a + / (1˜l) E{0¨(𝕨)𝕩}´ p # Primes in segment [a,b)
}
# Factor by trial division
r 0 # Result list
Try {
m (1+n) 2×𝕩 # Upper bound for factors this round
𝕩<m ? # Stop if no factors
primes np primes Sieve 𝕩m # New primes
{0=𝕩|n? r𝕩 n÷𝕩 𝕊𝕩 ;@}¨ np # Try each one
𝕊 m # Next segment
;@}
Try 2
r 1<n
}

View file

@ -0,0 +1,7 @@
> Factor¨ 1232123+4 # Some factored numbers
1232123 29 42487
1232124 2 2 3 102677
1232125 5 5 5 9857
1232126 2 7 17 31 167

View file

@ -0,0 +1,25 @@
@echo off
::usage: cmd /k primefactor.cmd number
setlocal enabledelayedexpansion
set /a compo=%1
if "%compo%"=="" goto:eof
set list=%compo%= (
set /a div=2 & call :loopdiv
set /a div=3 & call :loopdiv
set /a div=5,inc=2
:looptest
call :loopdiv
set /a div+=inc,inc=6-inc,div2=div*div
if %div2% lss %compo% goto looptest
if %compo% neq 1 set list= %list% %compo%
echo %list%) & goto:eof
:loopdiv
set /a "res=compo%%div
if %res% neq 0 goto:eof
set list=%list% %div%,
set/a compo/=div
goto:loopdiv

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,35 @@
// Factorization by trial division in C++11
#include <iostream>
#include <vector>
using long_pair = std::pair<long,long>;
using lp_vec = std::vector<long_pair>;
lp_vec factorize(long n)
{
lp_vec fs;
int cnt = 0;
for (;n%2==0; n/=2) cnt++; // optimized by compiler
if (cnt > 0)
fs.push_back({2, cnt});
for (long i=3; i*i<=n; i+=2) {
cnt = 0;
for (;n%i==0; n/=i) cnt++;
if (cnt>0)
fs.push_back({i, cnt});
}
if (n>1)
fs.push_back({n, 1});
return fs;
}
int main() {
long n;
std::cin >> n;
auto fs = factorize(n);
for (auto fp : fs) {
std::cout << fp.first << "^" << fp.second << "\n";
}
return 0;
}

View file

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
namespace PrimeDecomposition
{
class Program
{
static void Main(string[] args)
{
GetPrimes(12);
}
static List<int> GetPrimes(decimal n)
{
List<int> storage = new List<int>();
while (n > 1)
{
int i = 1;
while (true)
{
if (IsPrime(i))
{
if (((decimal)n / i) == Math.Round((decimal) n / i))
{
n /= i;
storage.Add(i);
break;
}
}
i++;
}
}
return storage;
}
static bool IsPrime(int n)
{
if (n <= 1) return false;
for (int i = 2; i <= Math.Sqrt(n); i++)
if (n % i == 0) return false;
return true;
}
}
}

View file

@ -0,0 +1,17 @@
using System.Collections.Generic;
namespace PrimeDecomposition
{
public class Primes
{
public List<int> FactorsOf(int n)
{
var factors = new List<int>();
for (var divisor = 2; n > 1; divisor++)
for (; n % divisor == 0; n /= divisor)
factors.Add(divisor);
return factors;
}
}

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,78 @@
typedef unsigned long long int ulong; // define a type that represent the limit (64-bit)
ulong mod_mul(ulong a, ulong b, const ulong mod) {
ulong res = 0, c; // return (a * b) % mod, avoiding overflow errors while doing modular multiplication.
for (b %= mod; a; a & 1 ? b >= mod - res ? res -= mod : 0, res += b : 0, a >>= 1, (c = b) >= mod - b ? c -= mod : 0, b += c);
return res % mod;
}
ulong mod_pow(ulong n, ulong exp, const ulong mod) {
ulong res = 1; // return (n ^ exp) % mod
for (n %= mod; exp; exp & 1 ? res = mod_mul(res, n, mod) : 0, n = mod_mul(n, n, mod), exp >>= 1);
return res;
}
ulong square_root(const ulong N) {
ulong res = 0, rem = N, c, d;
for (c = 1 << 62; c; c >>= 2) {
d = res + c;
res >>= 1;
if (rem >= d)
rem -= d, res += c;
} // returns the square root of N.
return res;
}
int is_prime(const ulong N) {
ulong i = 1; // return a truthy value about the primality of N.
if (N > 1) for (; i < 64 && mod_pow(i, N - 1, N) <= 1; ++i);
return i == 64;
}
ulong pollard_rho(const ulong N) {
// Require : N is a composite number, not a square.
// Ensure : res is a non-trivial factor of N.
// Option : change the timeout, change the rand function.
static const int timeout = 18;
static unsigned long long rand_val = 2994439072U;
rand_val = (rand_val * 1025416097U + 286824428U) % 4294967291LLU;
ulong res = 1, a, b, c, i = 0, j = 1, x = 1, y = 1 + rand_val % (N - 1);
for (; res == 1; ++i) {
if (i == j) {
if (j >> timeout)
break;
j <<= 1;
x = y;
}
a = y, b = y; // performs y = (y * y) % N
for (y = 0; a; a & 1 ? b >= N - y ? y -= N : 0, y += b : 0, a >>= 1, (c = b) >= N - b ? c -= N : 0, b += c);
y = (1 + y) % N;
for (a = y > x ? y - x : x - y, b = N; (a %= b) && (b %= a);); // compute the gcd(abs(y - x), N);
res = a | b;
}
return res;
}
void factor(const ulong N, ulong *array) {
// very basic manager that fill the given array (the size of the result is the first array element)
// it does not perform initial trial divisions, which is generally highly recommended.
if (N < 4 || is_prime(N)) {
if (N > 1 || !*array) array[++*array] = N;
return;
}
ulong x = square_root(N);
if (x * x != N) x = pollard_rho(N);
factor(x, array);
factor(N / x, array);
}
#include <stdio.h>
int main(void) {
// simple test.
unsigned long long n = 18446744073709551615U;
ulong fac[65] = {0};
factor(n, fac);
for (ulong i = 1; i <= *fac; ++i)
printf("* %llu\n", fac[i]);
}

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,17 @@
9000 REM ----- function generate
9010 REM in ... i ... number
9020 REM out ... pf() ... factors
9030 REM mod ... ca ... pf candidate
9040 pf(0)=0 : ca=2 : REM special case
9050 IF i=1 THEN RETURN
9060 IF INT(i/ca)*ca=i THEN GOSUB 9200 : GOTO 9050
9070 FOR ca=3 TO INT( SQR(i)) STEP 2
9080 IF i=1 THEN RETURN
9090 IF INT(i/ca)*ca=i THEN GOSUB 9200 : GOTO 9080
9100 NEXT
9110 IF i>1 THEN ca=i : GOSUB 9200
9120 RETURN
9200 pf(0)=pf(0)+1
9210 pf(pf(0))=ca
9220 i=i/ca
9230 RETURN

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,11 @@
;;; Tail-recursive version
(defun factor (n &optional (acc '()))
(when (> n 1) (loop with max-d = (isqrt n)
for d = 2 then (if (evenp d) (1+ d) (+ d 2)) do
(cond ((> d max-d) (return (cons (list n 1) acc)))
((zerop (rem n d))
(return (factor (truncate n d) (if (eq d (caar acc))
(cons
(list (caar acc) (1+ (cadar acc)))
(cdr acc))
(cons (list d 1) acc)))))))))

View file

@ -0,0 +1,27 @@
import std.stdio, std.bigint, std.algorithm, std.traits, std.range;
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() {
writefln("%(%s\n%)", iota(2, 10).map!decompose);
decompose(1023 * 1024).writeln;
BigInt(2 * 3 * 5 * 7 * 11 * 11 * 13 * 17).decompose.writeln;
decompose(16860167264933UL.BigInt * 179951).writeln;
decompose(2.BigInt ^^ 100_000).group.writeln;
}

View file

@ -0,0 +1,54 @@
program Prime_decomposition;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function IsPrime(n: UInt64): Boolean;
var
i: Integer;
begin
if n <= 1 then
exit(False);
i := 2;
while i < Sqrt(n) do
begin
if n mod i = 0 then
exit(False);
inc(i);
end;
Result := True;
end;
function GetPrimes(n: UInt64): TArray<UInt64>;
var
i: Integer;
begin
while n > 1 do
begin
i := 1;
while True do
begin
if IsPrime(i) then
begin
if n / i = (round(n / i)) then
begin
n := n div i;
SetLength(Result, Length(Result) + 1);
Result[High(Result)] := i;
Break;
end;
end;
inc(i);
end;
end;
end;
begin
for var v in GetPrimes(12) do
write(v, ' ');
readln;
end.

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,49 @@
PROGRAM DECOMPOSE
!
! for rosettacode.org
!
!VAR NUM,J
DIM PF[100]
PROCEDURE STORE_FACTOR
PF[0]=PF[0]+1
PF[PF[0]]=CA
I=I/CA
END PROCEDURE
PROCEDURE DECOMP(I)
PF[0]=0 CA=2 ! special case
LOOP
IF I=1 THEN EXIT PROCEDURE END IF
EXIT IF INT(I/CA)*CA<>I
STORE_FACTOR
END LOOP
FOR CA=3 TO INT(SQR(I)) STEP 2 DO
LOOP
IF I=1 THEN EXIT PROCEDURE END IF
EXIT IF INT(I/CA)*CA<>I
STORE_FACTOR
END LOOP
END FOR
IF I>1 THEN CA=I STORE_FACTOR END IF
END PROCEDURE
BEGIN
! ----- function generate
! in ... I ... number
! out ... PF[] ... factors
! PF[0] ... # of factors
! mod ... CA ... pr.fact. candidate
PRINT(CHR$(12);) !CLS
INPUT("Numero ",NUM)
DECOMP(NUM)
PRINT(NUM;"=";)
FOR J=1 TO PF[0] DO
PRINT(PF[J];)
END FOR
PRINT
END PROGRAM

View file

@ -0,0 +1,15 @@
proc decompose num . primes[] .
primes[] = [ ]
t = 2
while t * t <= num
if num mod t = 0
primes[] &= t
num = num / t
else
t += 1
.
.
primes[] &= num
.
call decompose 9007199254740991 r[]
print r[]

View file

@ -0,0 +1,10 @@
(prime-factors 1024)
→ (2 2 2 2 2 2 2 2 2 2)
(lib 'bigint)
;; 2^59 - 1
(prime-factors (1- (expt 2 59)))
→ (179951 3203431780337)
(prime-factors 100000000000000000037)
→ (31 821 66590107 59004541)

View file

@ -0,0 +1,39 @@
class
PRIME_DECOMPOSITION
feature
factor (p: INTEGER): ARRAY [INTEGER]
-- Prime decomposition of 'p'.
require
p_positive: p > 0
local
div, i, next, rest: INTEGER
do
create Result.make_empty
if p = 1 then
Result.force (1, 1)
end
div := 2
next := 3
rest := p
from
i := 1
until
rest = 1
loop
from
until
rest \\ div /= 0
loop
Result.force (div, i)
rest := (rest / div).floor
i := i + 1
end
div := next
next := next + 2
end
ensure
is_divisor: across Result as r all p \\ r.item = 0 end
is_prime: across Result as r all prime (r.item) end
end

View file

@ -0,0 +1,9 @@
open integer //arbitrary sized integers
decompose_prime n = loop n 2I
where
loop c p | c < (p * p) = [c]
| c % p == 0I = p :: (loop (c / p) p)
| else = loop c (p + 1I)
decompose_prime 600851475143I

View file

@ -0,0 +1,15 @@
defmodule Prime do
def decomposition(n), do: decomposition(n, 2, [])
defp decomposition(n, k, acc) when n < k*k, do: Enum.reverse(acc, [n])
defp decomposition(n, k, acc) when rem(n, k) == 0, do: decomposition(div(n, k), k, [k | acc])
defp decomposition(n, k, acc), do: decomposition(n, k+1, acc)
end
prime = Stream.iterate(2, &(&1+1)) |>
Stream.filter(fn n-> length(Prime.decomposition(n)) == 1 end) |>
Enum.take(17)
mersenne = Enum.map(prime, fn n -> {n, round(:math.pow(2,n)) - 1} end)
Enum.each(mersenne, fn {n,m} ->
:io.format "~3s :~20w = ~s~n", ["M#{n}", m, Prime.decomposition(m) |> Enum.join(" x ")]
end)

View file

@ -0,0 +1,11 @@
% no stack consuming version
factors(N) ->
factors(N,2,[]).
factors(1,_,Acc) -> Acc;
factors(N,K,Acc) when N < K*K -> [N|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,143 @@
## இந்த நிரல் தரப்பட்ட எண்ணின் பகாஎண் கூறுகளைக் கண்டறியும்
நிரல்பாகம் பகாஎண்ணா(எண்1)
## இந்த நிரல்பாகம் தரப்பட்ட எண் பகு எண்ணா அல்லது பகா எண்ணா என்று கண்டறிந்து சொல்லும்
## பகுஎண் என்றால் 0 திரும்பத் தரப்படும்
## பகாஎண் என்றால் 1 திரும்பத் தரப்படும்
@(எண்1 < 0) ஆனால்
## எதிர்மறை எண்களை நேராக்குதல்
எண்1 = எண்1 * (-1)
முடி
@(எண்1 < 2) ஆனால்
## பூஜ்ஜியம், ஒன்று ஆகியவை பகா எண்கள் அல்ல
பின்கொடு 0
முடி
@(எண்1 == 2) ஆனால்
## இரண்டு என்ற எண் ஒரு பகா எண்
பின்கொடு 1
முடி
மீதம் = எண்1%2
@(மீதம் == 0) ஆனால்
## இரட்டைப்படை எண், ஆகவே, இது பகா எண் அல்ல
பின்கொடு 0
முடி
எண்1வர்க்கமூலம் = எண்1^0.5
@(எண்2 = 3, எண்2 <= எண்1வர்க்கமூலம், எண்2 = எண்2 + 2) ஆக
மீதம்1 = எண்1%எண்2
@(மீதம்1 == 0) ஆனால்
## ஏதேனும் ஓர் எண்ணால் முழுமையாக வகுபட்டுவிட்டது, ஆகவே அது பகா எண் அல்ல
பின்கொடு 0
முடி
முடி
பின்கொடு 1
முடி
நிரல்பாகம் பகுத்தெடு(எண்1)
## இந்த எண் தரப்பட்ட எண்ணின் பகா எண் கூறுகளைக் கண்டறிந்து பட்டியல் இடும்
கூறுகள் = பட்டியல்()
@(எண்1 < 0) ஆனால்
## எதிர்மறை எண்களை நேராக்குதல்
எண்1 = எண்1 * (-1)
முடி
@(எண்1 <= 1) ஆனால்
## ஒன்று அல்லது அதற்குக் குறைவான எண்களுக்குப் பகா எண் விகிதம் கண்டறியமுடியாது
பின்கொடு கூறுகள்
முடி
@(பகாஎண்ணா(எண்1) == 1) ஆனால்
## தரப்பட்ட எண்ணே பகா எண்ணாக அமைந்துவிட்டால், அதற்கு அதுவே பகாஎண் கூறு ஆகும்
பின்இணை(கூறுகள், எண்1)
பின்கொடு கூறுகள்
முடி
தாற்காலிகஎண் = எண்1
எண்2 = 2
@(எண்2 <= தாற்காலிகஎண்) வரை
விடை1 = பகாஎண்ணா(எண்2)
மீண்டும்தொடங்கு = 0
@(விடை1 == 1) ஆனால்
விடை2 = தாற்காலிகஎண்%எண்2
@(விடை2 == 0) ஆனால்
## பகா எண்ணால் முழுமையாக வகுபட்டுள்ளது, அதனைப் பட்டியலில் இணைக்கிறோம்
பின்இணை(கூறுகள், எண்2)
தாற்காலிகஎண் = தாற்காலிகஎண்/எண்2
## மீண்டும் இரண்டில் தொடங்கி இதே கணக்கிடுதலைத் தொடரவேண்டும்
எண்2 = 2
மீண்டும்தொடங்கு = 1
முடி
முடி
@(மீண்டும்தொடங்கு == 0) ஆனால்
## அடுத்த எண்ணைத் தேர்ந்தெடுத்துக் கணக்கிடுதலைத் தொடரவேண்டும்
எண்2 = எண்2 + 1
முடி
முடி
பின்கொடு கூறுகள்
முடி
அ = int(உள்ளீடு("உங்களுக்குப் பிடித்த ஓர் எண்ணைத் தாருங்கள்: "))
பகாஎண்கூறுகள் = பட்டியல்()
பகாஎண்கூறுகள் = பகுத்தெடு(அ)
பதிப்பி "நீங்கள் தந்த எண்ணின் பகா எண் கூறுகள் இவை: ", பகாஎண்கூறுகள்

View file

@ -0,0 +1,9 @@
let decompose_prime n =
let rec loop c p =
if c < (p * p) then [c]
elif c % p = 0I then p :: (loop (c/p) p)
else loop c (p + 1I)
loop n 2I
printfn "%A" (decompose_prime 600851475143I)

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,53 @@
' FB 1.05.0 Win64
Function isPrime(n As Integer) As Boolean
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim d As Integer = 5
While d * d <= n
If n Mod d = 0 Then Return False
d += 2
If n Mod d = 0 Then Return False
d += 4
Wend
Return True
End Function
Sub getPrimeFactors(factors() As UInteger, n As UInteger)
If n < 2 Then Return
If isPrime(n) Then
Redim factors(0 To 0)
factors(0) = n
Return
End If
Dim factor As UInteger = 2
Do
If n Mod factor = 0 Then
Redim Preserve factors(0 To UBound(factors) + 1)
factors(UBound(factors)) = factor
n \= factor
If n = 1 Then Return
If isPrime(n) Then factor = n
Else
factor += 1
End If
Loop
End Sub
Dim factors() As UInteger
Dim primes(1 To 17) As UInteger = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59}
Dim n As UInteger
For i As UInteger = 1 To 17
Erase factors
n = 1 Shl primes(i) - 1
getPrimeFactors factors(), n
Print "2^";Str(primes(i)); Tab(5); " - 1 = "; Str(n); Tab(30);" => ";
For j As UInteger = LBound(factors) To UBound(factors)
Print factors(j);
If j < UBound(factors) Then Print " x ";
Next j
Print
Next i
Print
Print "Press any key to quit"
Sleep

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,5 @@
factorize n = [ d | p <- [2..n], isPrime p, d <- divs n p ]
-- [2..n] >>= (\p-> [p|isPrime p]) >>= divs n
where
divs n p | rem n p == 0 = p : divs (quot n p) p
| otherwise = []

View file

@ -0,0 +1,11 @@
import Data.Maybe (listToMaybe)
import Data.List (unfoldr)
factorize :: Integer -> [Integer]
factorize n
= unfoldr (\n -> listToMaybe [(x, div n x) | x <- [2..n], mod n x==0]) n
= unfoldr (\(d,n) -> listToMaybe [(x, (x, div n x)) | x <- [d..n], mod n x==0]) (2,n)
= unfoldr (\(d,n) -> listToMaybe [(x, (x, div n x)) | x <-
takeWhile ((<=n).(^2)) [d..] ++ [n|n>1], mod n x==0]) (2,n)
= unfoldr (\(ds,n) -> listToMaybe [(x, (dropWhile (< x) ds, div n x)) | n>1, x <-
takeWhile ((<=n).(^2)) ds ++ [n|n>1], mod n x==0]) (primesList,n)

View file

@ -0,0 +1,6 @@
factorize n = divs n primesList
where
divs n ds@(d:t) | d*d > n = [n | n > 1]
| r == 0 = d : divs q ds
| otherwise = divs 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,2 @@
q: 3684
2 2 3 307

View file

@ -0,0 +1,6 @@
_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,43 @@
private static final BigInteger TWO = BigInteger.valueOf(2);
private static final BigInteger THREE = BigInteger.valueOf(3);
private static final BigInteger FIVE = BigInteger.valueOf(5);
public static ArrayList<BigInteger> primeDecomp(BigInteger n){
if(n.compareTo(TWO) < 0) return null;
ArrayList<BigInteger> factors = new ArrayList<BigInteger>();
// handle even values
while(n.and(BigInteger.ONE).equals(BigInteger.ZERO)){
n = n.shiftRight(1);
factors.add(TWO);
}
// handle values divisible by three
while(n.mod(THREE).equals(BigInteger.ZERO)){
factors.add(THREE);
n = n.divide(THREE);
}
// handle values divisible by five
while(n.mod(FIVE).equals(BigInteger.ZERO)){
factors.add(FIVE);
n = n.divide(FIVE);
}
// much like how we can skip multiples of two, we can also skip
// multiples of three and multiples of five. This increment array
// helps us to accomplish that
int[] pattern = {4,2,4,2,4,6,2,6};
int pattern_index = 0;
BigInteger current_test = BigInteger.valueOf(7);
while(!n.equals(BigInteger.ONE)){
while(n.mod(current_test).equals(BigInteger.ZERO)){
factors.add(current_test);
n = n.divide(current_test);
}
current_test = current_test.add(BigInteger.valueOf(pattern[pattern_index]));
pattern_index = (pattern_index + 1) & 7;
}
return factors;
}

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,40 @@
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 + 6); 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,14 @@
function factors(n) {
if (!n || n < 2)
return [];
var f = [];
for (var i = 2; i <= n; i++){
while (n % i === 0){
f.push(i);
n /= i;
}
}
return f;
};

View file

@ -0,0 +1,48 @@
/// <reference path="PrimeFactors.js" />
describe("Prime Factors", function() {
it("Given nothing, empty is returned", function() {
expect(factors()).toEqual([]);
});
it("Given 1, empty is returned", function() {
expect(factors(1)).toEqual([]);
});
it("Given 2, 2 is returned", function() {
expect(factors(2)).toEqual([2]);
});
it("Given 3, 3 is returned", function() {
expect(factors(3)).toEqual([3]);
});
it("Given 4, 2 and 2 is returned", function() {
expect(factors(4)).toEqual([2, 2]);
});
it("Given 5, 5 is returned", function() {
expect(factors(5)).toEqual([5]);
});
it("Given 6, 2 and 3 is returned", function() {
expect(factors(6)).toEqual([2, 3]);
});
it("Given 7, 7 is returned", function() {
expect(factors(7)).toEqual([7]);
});
it("Given 8; 2, 2, and 2 is returned", function() {
expect(factors(8)).toEqual([2, 2, 2]);
});
it("Given a large number, many primes factors are returned", function() {
expect(factors(2*2*2*3*3*7*11*17))
.toEqual([2, 2, 2, 3, 3, 7, 11, 17]);
});
it("Given a large prime number, that number is returned", function() {
expect(factors(997)).toEqual([997]);
});
});

View file

@ -0,0 +1,14 @@
def factors:
. as $in
| [2, $in, false]
| recurse(
. as [$p, $q, $valid, $s]
| if $q == 1 then empty
elif $q % $p == 0 then [$p, $q/$p, true]
elif $p == 2 then [3, $q, false, $s]
else ($s // ($q | sqrt)) as $s
| if $p + 2 <= $s then [$p + 2, $q, false, $s]
else [$q, 1, true]
end
end )
| if .[2] then .[0] else empty end ;

View file

@ -0,0 +1,9 @@
24 | factors
#=> 2 2 2 3
[9007199254740992 | factors] | length
#=> 53
# 2**29-1 is 536870911
[ 536870911 | factors ]
#=> [233,1103,2089]

View file

@ -0,0 +1,3 @@
julia> Pkg.add("Primes")
julia> factor(8796093022207)
[9719=>1,431=>1,2099863=>1]

View file

@ -0,0 +1,35 @@
// version 1.0.6
import java.math.BigInteger
val bigTwo = BigInteger.valueOf(2L)
val bigThree = BigInteger.valueOf(3L)
fun getPrimeFactors(n: BigInteger): MutableList<BigInteger> {
val factors = mutableListOf<BigInteger>()
if (n < bigTwo) return factors
if (n.isProbablePrime(20)) {
factors.add(n)
return factors
}
var factor = bigTwo
var nn = n
while (true) {
if (nn % factor == BigInteger.ZERO) {
factors.add(factor)
nn /= factor
if (nn == BigInteger.ONE) return factors
if (nn.isProbablePrime(20)) factor = nn
}
else if (factor >= bigThree) factor += bigTwo
else factor = bigThree
}
}
fun main(args: Array<String>) {
val primes = intArrayOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
for (prime in primes) {
val bigPow2 = bigTwo.pow(prime) - BigInteger.ONE
println("2^${"%2d".format(prime)} - 1 = ${bigPow2.toString().padEnd(30)} => ${getPrimeFactors(bigPow2)}")
}
}

View file

@ -0,0 +1,10 @@
(defun factors (n)
(factors n 2 '()))
(defun factors
((1 _ acc)
acc)
((n k acc) (when (== 0 (rem n k)))
(factors (div n k) k (cons k acc)))
((n k acc)
(factors n (+ k 1) acc)))

View file

@ -0,0 +1,31 @@
{def prime_fact.smallest
{def prime_fact.smallest.r
{lambda {:q :r :i}
{if {and {> :r 0} {< :i :q}}
then {prime_fact.smallest.r :q {% :q {+ :i 1}} {+ :i 1}}
else :i}}}
{lambda {:q} {prime_fact.smallest.r :q {% :q 2} 2}}}
{def prime_fact
{def prime_fact.r
{lambda {:q :d}
{if {> :q 1}
then {let { {:q :q} {:d :d}
{:i {prime_fact.smallest :q}}}
{prime_fact.r {floor {/ :q :i}} {#.push! :d :i}} }
else {if {= {#.length :d} 1} then {b :d} else :d}}}}
{lambda {:n} :n:{prime_fact.r :n {#.new}}}}
{prime_fact {* 2 3 3 3 31 47 173}}
-> 13611294:[2,3,3,3,31,47,173]
{map prime_fact {serie 2 101}}
-> 2:[2] 3:[3] 4:[2,2] 5:[5] 6:[2,3] 7:[7] 8:[2,2,2] 9:[3,3] 10:[2,5] 11:[11] 12:[2,2,3] 13:[13] 14:[2,7] 15:[3,5]
16:[2,2,2,2] 17:[17] 18:[2,3,3] 19:[19] 20:[2,2,5] 21:[3,7] 22:[2,11] 23:[23] 24:[2,2,2,3] 25:[5,5] 26:[2,13] 27:[3,3,3]
28:[2,2,7] 29:[29] 30:[2,3,5] 31:[31] 32:[2,2,2,2,2] 33:[3,11] 34:[2,17] 35:[5,7] 36:[2,2,3,3] 37:[37] 38:[2,19] 39:[3,13]
40:[2,2,2,5] 41:[41] 42:[2,3,7] 43:[43] 44:[2,2,11] 45:[3,3,5] 46:[2,23] 47:[47] 48:[2,2,2,2,3] 49:[7,7] 50:[2,5,5] 51:[3,17]
52:[2,2,13] 53:[53] 54:[2,3,3,3] 55:[5,11] 56:[2,2,2,7] 57:[3,19] 58:[2,29] 59:[59] 60:[2,2,3,5] 61:[61] 62:[2,31] 63:[3,3,7]
64:[2,2,2,2,2,2] 65:[5,13] 66:[2,3,11] 67:[67] 68:[2,2,17] 69:[3,23] 70:[2,5,7] 71:[71] 72:[2,2,2,3,3] 73:[73] 74:[2,37]
75:[3,5,5] 76:[2,2,19] 77:[7,11] 78:[2,3,13] 79:[79] 80:[2,2,2,2,5] 81:[3,3,3,3] 82:[2,41] 83:[83] 84:[2,2,3,7] 85:[5,17]
86:[2,43] 87:[3,29] 88:[2,2,2,11] 89:[89] 90:[2,3,3,5] 91:[7,13] 92:[2,2,23] 93:[3,31] 94:[2,47] 95:[5,19] 96:[2,2,2,2,2,3]
97:[97] 98:[2,7,7] 99:[3,3,11] 100:[2,2,5,5] 101:[101]

View file

@ -0,0 +1,23 @@
-- Returns list of prime factors for given number.
-- To overcome the limits of integers (signed 32-bit in Lingo),
-- the number can be specified as float (which works up to 2^53).
-- For the same reason, values in returned list are floats, not integers.
on getPrimeFactors (n)
f = []
f.sort()
c = sqrt(n)
i = 1.0
repeat while TRUE
i=i+1
if i>c then exit repeat
check = n/i
if bitOr(check,0)=check then
f.add(i)
n = check
c = sqrt(n)
i = 1.0
end if
end repeat
f.add(n)
return f
end

View file

@ -0,0 +1,11 @@
put getPrimeFactors(12)
-- [2.0000, 2.0000, 3.0000]
-- print floats without fractional digits
the floatPrecision=0
put getPrimeFactors(12)
-- [2, 2, 3]
put getPrimeFactors(1125899906842623.0)
-- [3, 251, 601, 4051, 614141]

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,50 @@
Module Prime_decomposition {
Inventory Known1=2@, 3@
IsPrime=lambda Known1 (x as decimal) -> {
=0=1
if exist(Known1, x) then =1=1 : exit
if x<=5 OR frac(x) then {if x == 2 OR x == 3 OR x == 5 then Append Known1, x : =1=1
Break}
if frac(x/2) else exit
if frac(x/3) else exit
x1=sqrt(x):d = 5@
{if frac(x/d ) else exit
d += 2: if d>x1 then Append Known1, x : =1=1 : exit
if frac(x/d) else exit
d += 4: if d<= x1 else Append Known1, x : =1=1: exit
loop}
}
decompose=lambda IsPrime (n as decimal) -> {
Inventory queue Factors
{
k=2@
While frac(n/k)=0 {
n/=k
Append Factors, k
}
if n=1 then exit
k++
While frac(n/k)=0 {
n/=k
Append Factors, k
}
if n=1 then exit
{
k+=2
while not isprime(k) {k+=2}
While frac(n/k)=0 {
n/=k
Append Factors, k
}
if n=1 then exit
loop
}
}
=Factors
}
Data 10, 100, 12, 144, 496, 1212454
while not empty {
Print Decompose(Number)
}
}
Prime_decomposition

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,2 @@
> ifactor(1337);
(7) (191)

View file

@ -0,0 +1,2 @@
> ifactors(1337);
[1, [[7, 1], [191, 1]]]

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

Some files were not shown because too many files have changed in this diff Show more