Prime decomposition: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 37:
{{trans|D}}
 
<langsyntaxhighlight lang="11l">F decompose(BigInt number)
[BigInt] result
V n = number
Line 58:
print(decompose(1023 * 1024))
print(decompose(2 * 3 * 5 * 7 * 11 * 11 * 13 * 17))
print(decompose(BigInt(16860167264933) * 179951))</langsyntaxhighlight>
 
{{out}}
Line 77:
=={{header|360 Assembly}}==
For maximum compatibility, this program uses only the basic instruction set.
<langsyntaxhighlight lang="360asm">PRIMEDE CSECT
USING PRIMEDE,R13
B 80(R15) skip savearea
Line 152:
WDECO DS CL16
YREGS
END PRIMEDE</langsyntaxhighlight>
{{out}}
<pre>
Line 160:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program primeDecomp64.s */
Line 386:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 397:
 
=={{header|ABAP}}==
<langsyntaxhighlight ABAPlang="abap">class ZMLA_ROSETTA definition
public
create public .
Line 449:
ENDIF.
endmethod.
ENDCLASS.</langsyntaxhighlight>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(include-book "arithmetic-3/top" :dir :system)
 
(defun prime-factors-r (n i)
Line 464:
(defun prime-factors (n)
(declare (xargs :mode :program))
(prime-factors-r n 2))</langsyntaxhighlight>
 
=={{header|Ada}}==
Line 474:
This is the specification of the generic package '''Prime_Numbers''':
 
<langsyntaxhighlight lang="ada">generic
type Number is private;
Zero : Number;
Line 488:
function Decompose (N : Number) return Number_List;
function Is_Prime (N : Number) return Boolean;
end Prime_Numbers;</langsyntaxhighlight>
 
The function Decompose first estimates the maximal result length as log<sub>2</sub> of the argument. Then it allocates the result and starts to enumerate divisors. It does not care to check if the divisors are prime, because non-prime divisors will be automatically excluded.
Line 494:
This is the implementation of the generic package '''Prime_Numbers''':
 
<langsyntaxhighlight lang="ada">package body Prime_Numbers is
-- auxiliary (internal) functions
function First_Factor (N : Number; Start : Number) return Number is
Line 524:
function Is_Prime (N : Number) return Boolean is
(N > One and then First_Factor(N, Two)=N);
end Prime_Numbers;</langsyntaxhighlight>
 
In the example provided, the package '''Prime_Numbers''' is instantiated with plain integer type:
 
<langsyntaxhighlight lang="ada">with Prime_Numbers, Ada.Text_IO;
procedure Test_Prime is
Line 545:
begin
Put (Decompose (12));
end Test_Prime;</langsyntaxhighlight>
 
{{out}} (decomposition of 12):
Line 561:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
 
<langsyntaxhighlight lang="algol68">#IF long int possible THEN #
 
MODE LINT = LONG INT;
Line 663:
# OD # ));
done: EMPTY
)</langsyntaxhighlight>
{{out}}
<pre>
Line 689:
Sadly, ALGOL-M does not allow arrays to be passed as parameters to procedures or functions, so the routine
must store its results in (and know the name of) the external array used for that purpose.
<syntaxhighlight lang="algol">
<lang ALGOL>
BEGIN
 
Line 742:
 
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 760:
 
=={{header|Applesoft BASIC}}==
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">9040 PF(0) = 0 : SC = 0
9050 FOR CA = 2 TO INT( SQR(I))
9060 IF I = 1 THEN RETURN
Line 772:
9210 PF(PF(0)) = CA
9220 I = I / CA
9230 RETURN</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">decompose: function [num][
facts: to [:string] factors.prime num
print [
Line 784:
]
 
loop 2..40 => decompose</langsyntaxhighlight>
 
{{out}}
Line 829:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % factor(8388607) ; 47 * 178481
factor(n)
Line 845:
f++
}
}</langsyntaxhighlight>
===Optimized Version===
{{trans|JavaScript}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">prime_numbers(n) {
if (n <= 3)
return [n]
Line 890:
ans.push(n)
return ans
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">num := 8388607, output := ""
for i, p in prime_numbers(num)
output .= p " * "
MsgBox % num " = " Trim(output, " * ")
return</langsyntaxhighlight>
{{out}}
<pre>8388607 = 47 * 178481</pre>
Line 903:
As the examples show, pretty large numbers can be factored in tolerable time:
 
<langsyntaxhighlight lang="awk"># Usage: awk -f primefac.awk
function pfac(n, r, f){
r = ""; f = 2
Line 918:
# For each line of input, print the prime factors.
{ print pfac($1) }
</syntaxhighlight>
</lang>
{{out}} entering input on stdin:
<pre>$
Line 932:
=={{header|Batch file}}==
Unfortunately Batch does'nt have a BigNum library so the maximum number that can be decomposed is 2^31-1
<langsyntaxhighlight Batchlang="batch file">
@echo off
::usage: cmd /k primefactor.cmd number
Line 958:
set/a compo/=div
goto:loopdiv
</syntaxhighlight>
</lang>
 
=={{header|Befunge}}==
{{works_with|befungee}}
Handles safely integers only up to 250 (or ones which don't have prime divisors greater than 250).
<langsyntaxhighlight Befungelang="befunge">& 211p > : 1 - #v_ 25*, @ > 11g:. / v
> : 11g %!|
> 11g 1+ 11p v
^ <</langsyntaxhighlight>
 
=={{header|BQN}}==
An efficient <code>Factor</code> function using trial division and Pollard's rho algorithm is given in bqn-libs [https://github.com/mlochbaum/bqn-libs/blob/master/primes.bqn primes.bqn]. The following standalone version is based on the trial division there, and builds in the sieve from [[Extensible prime generator#BQN|Extensible prime generator]].
<langsyntaxhighlight lang="bqn">Factor ← { 𝕊n:
# Prime sieve
primes ← ↕0
Line 989:
Try 2
r ∾ 1⊸<⊸⥊n
}</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="bqn"> > ⋈⟜Factor¨ 1232123+↕4 # Some factored numbers
┌─
╵ 1232123 ⟨ 29 42487 ⟩
Line 997:
1232125 ⟨ 5 5 5 9857 ⟩
1232126 ⟨ 2 7 17 31 167 ⟩
┘</langsyntaxhighlight>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) 12fC
{2 2 3}
</syntaxhighlight>
</lang>
 
=={{header|C}}==
Line 1,011:
 
Relatively sophiscated sieve method based on size 30 prime wheel. The code does not pretend to handle prime factors larger than 64 bits. All 32-bit primes are cached with 137MB data. Cache data takes about a minute to compute the first time the program is run, which is also saved to the current directory, and will be loaded in a second if needed again.
<langsyntaxhighlight lang="c">#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
Line 1,181:
 
return 0;
}</langsyntaxhighlight>
 
===Using GNU Compiler Collection gcc extensions===
Line 1,193:
way, and in the case of this sample it requires the GCC "nested procedure"
extension to the C language.
<langsyntaxhighlight lang="c">#include <limits.h>
#include <stdio.h>
#include <math.h>
Line 1,299:
CONTINUE;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,322:
Note: gcc took 487,719 BogoMI to complete the example.
 
To understand what was going on with the above code, pass it through <code>cpp</code> and read the outcome. Translated into normal C code sans the function call overhead, it's really this (the following uses a adjustable cache, although setting it beyond a few thousands doesn't gain further benefit):<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
Line 1,394:
return 0;
}</langsyntaxhighlight>
 
 
===Version 2===
<syntaxhighlight lang="c">
<lang c>
typedef unsigned long long int ulong; // define a type that represent the limit (64-bit)
 
Line 1,478:
}
 
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 1,524:
}
}
}</langsyntaxhighlight>
 
===Simple trial division===
Line 1,530:
Although this three-line algorithm does not mention anything about primes, the fact that factors are taken out of the number <code>n</code> in ascending order garantees the list will only contain primes.
 
<langsyntaxhighlight lang="csharp">using System.Collections.Generic;
 
namespace PrimeDecomposition
Line 1,546:
return factors;
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{works with|g++|4.1.2 20061115 (prerelease) (Debian 4.1.1-21)}}
{{libheader|GMP}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <gmpxx.h>
 
Line 1,635:
std::cout << "\n";
}
}</langsyntaxhighlight>
 
=== Simple trial division ===
<langsyntaxhighlight lang="cpp">// Factorization by trial division in C++11
 
#include <iostream>
Line 1,672:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">;;; No stack consuming algorithm
(defn factors
"Return a list of factors of N."
Line 1,685:
(if (= 0 (rem n k))
(recur (quot n k) k (cons k acc))
(recur n (inc k) acc)))))</langsyntaxhighlight>
 
=={{header|Commodore BASIC}}==
{{works_with|Commodore BASIC|2.0}}
It's not easily possible to have arbitrary precision integers in PET basic, so here is at least a version using built-in data types (reals). On return from the subroutine starting at 9000 the global array pf contains the number of factors followed by the factors themselves:
<langsyntaxhighlight lang="zxbasic">9000 REM ----- function generate
9010 REM in ... i ... number
9020 REM out ... pf() ... factors
Line 1,706:
9210 pf(pf(0))=ca
9220 i=i/ca
9230 RETURN</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight Lisplang="lisp">;;; Recursive algorithm
(defun factor (n)
"Return a list of factors of N."
Line 1,716:
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)))))))))</langsyntaxhighlight>
 
<langsyntaxhighlight Lisplang="lisp">;;; Tail-recursive version
(defun factor (n &optional (acc '()))
(when (> n 1) (loop with max-d = (isqrt n)
Line 1,728:
(list (caar acc) (1+ (cadar acc)))
(cdr acc))
(cons (list d 1) acc)))))))))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.bigint, std.algorithm, std.traits, std.range;
 
Unqual!T[] decompose(T)(in T number) pure nothrow
Line 1,757:
decompose(16860167264933UL.BigInt * 179951).writeln;
decompose(2.BigInt ^^ 100_000).group.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[2]
Line 1,774:
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Prime_decomposition;
 
Line 1,828:
write(v, ' ');
readln;
end.</langsyntaxhighlight>
 
=={{header|E}}==
Line 1,834:
This example assumes a function <code>isPrime</code> and was tested with [[Primality by Trial Division#E|this one]]. It could use a self-referential implementation such as the Python task, but the original author of this example did not like the ordering dependency involved.
 
<langsyntaxhighlight lang="e">def primes := {
var primesCache := [2]
/** A collection of all prime numbers. */
Line 1,862:
}
return factors
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
The built-in '''prime-factors''' function performs the task.
<langsyntaxhighlight lang="lisp">(prime-factors 1024)
→ (2 2 2 2 2 2 2 2 2 2)
 
Line 1,875:
 
(prime-factors 100000000000000000037)
→ (31 821 66590107 59004541)</langsyntaxhighlight>
 
=={{header|Eiffel}}==
Uses the feature prime from the Task Primality by Trial Devision in the contract to check if the Result contains only prime numbers.
<langsyntaxhighlight Eiffellang="eiffel">class
PRIME_DECOMPOSITION
 
Line 1,917:
is_divisor: across Result as r all p \\ r.item = 0 end
is_prime: across Result as r all prime (r.item) end
end</langsyntaxhighlight>
 
The test was done in an application class. (Similar as in other Eiffel examples (ex. Selectionsort).)
Line 1,929:
=={{header|Ela}}==
{{trans|F#}}
<langsyntaxhighlight lang="ela">open integer //arbitrary sized integers
 
decompose_prime n = loop n 2I
Line 1,937:
| else = loop c (p + 1I)
 
decompose_prime 600851475143I</langsyntaxhighlight>
 
{{out}}<pre>[71,839,1471,6857]</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Prime do
def decomposition(n), do: decomposition(n, 2, [])
Line 1,956:
Enum.each(mersenne, fn {n,m} ->
:io.format "~3s :~20w = ~s~n", ["M#{n}", m, Prime.decomposition(m) |> Enum.join(" x ")]
end)</langsyntaxhighlight>
 
{{out}}
Line 1,979:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">% no stack consuming version
 
factors(N) ->
Line 1,989:
factors(N div K,K, [K|Acc]);
factors(N,K,Acc) ->
factors(N,K+1,Acc).</langsyntaxhighlight>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM DECOMPOSE
 
Line 2,042:
PRINT
END PROGRAM
</syntaxhighlight>
</lang>
This version is a translation from Commodore BASIC program.
 
=={{header|Ezhil}}==
<syntaxhighlight lang="ezhil">
<lang Ezhil>
## இந்த நிரல் தரப்பட்ட எண்ணின் பகாஎண் கூறுகளைக் கண்டறியும்
 
Line 2,190:
 
பதிப்பி "நீங்கள் தந்த எண்ணின் பகா எண் கூறுகள் இவை: ", பகாஎண்கூறுகள்
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight Fsharplang="fsharp">let decompose_prime n =
let rec loop c p =
if c < (p * p) then [c]
Line 2,201:
loop n 2I
printfn "%A" (decompose_prime 600851475143I)</langsyntaxhighlight>
{{out}}
<pre>[71; 839; 1471; 6857]</pre>
Line 2,207:
=={{header|Factor}}==
<code>factors</code> from the <code>math.primes.factors</code> vocabulary converts a number into a sequence of its prime divisors; the rest of the code prints this sequence.
<langsyntaxhighlight lang="factor">USING: io kernel math math.parser math.primes.factors sequences ;
 
27720 factors
[ number>string ] map
" " join print ;</langsyntaxhighlight>
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">[2[\$@$$*@>~][\$@$@$@$@\/*=$[%$." "$@\/\0~]?~[1+1|]?]#%.]d:
27720d;! {2 2 2 3 3 5 7 11}</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: decomp ( n -- )
2
begin 2dup dup * >=
Line 2,226:
then
repeat
drop . ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">module PrimeDecompose
implicit none
 
Line 2,260:
end subroutine find_factors
 
end module PrimeDecompose</langsyntaxhighlight>
 
<langsyntaxhighlight lang="fortran">program Primes
use PrimeDecompose
implicit none
Line 2,278:
end do
 
end program Primes</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function isPrime(n As Integer) As Boolean
Line 2,333:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,359:
Frink has a built-in factoring function which uses wheel factoring, trial division, Pollard p-1 factoring, and Pollard rho factoring.
It also recognizes some special forms (e.g. Mersenne numbers) and handles them efficiently.
<langsyntaxhighlight lang="frink">println[factor[2^508-1]]</langsyntaxhighlight>
 
{{out}} (total process time including JVM startup = 1.515 s):
Line 2,370:
=={{header|GAP}}==
Built-in function :
<langsyntaxhighlight lang="gap">FactorsInt(2^67-1);
# [ 193707721, 761838257287 ]</langsyntaxhighlight>
Or using the [http://www.gap-system.org/Manuals/pkg/factint/doc/chap0.html FactInt] package :
<langsyntaxhighlight lang="gap">FactInt(2^67-1);
# [ [ 193707721, 761838257287 ], [ ] ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,415:
fmt.Println(v, "->", Primes(big.NewInt(v)))
}
}</langsyntaxhighlight>
{{out}}
<pre>2147483648 -> [2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]
Line 2,428:
so it does not require an "isPrime-like function",
assumed or otherwise.
<langsyntaxhighlight lang="groovy">def factorize = { long target ->
if (target == 1) return [1L]
Line 2,456:
}
primeFactors
}</langsyntaxhighlight>
 
{{out|Test #1}}
<langsyntaxhighlight lang="groovy">((1..30) + [97*4, 1000, 1024, 333333]).each { println ([number:it, primes:decomposePrimes(it)]) }</langsyntaxhighlight>
 
{{out|Output #1}}
Line 2,498:
 
{{out|Test #2}}
<langsyntaxhighlight lang="groovy">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)]) }</langsyntaxhighlight>
 
{{out|Output #2}}
Line 2,524:
The task description hints at using the <code>isPrime</code> function from the [[Primality by trial division#Haskell|trial division]] task:
 
<langsyntaxhighlight lang="haskell">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 = []</langsyntaxhighlight>
 
but it is not very efficient, to put it mildly. Inlining and fusing gets us the progressively more optimized
<langsyntaxhighlight lang="haskell">import Data.Maybe (listToMaybe)
import Data.List (unfoldr)
 
Line 2,541:
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)</langsyntaxhighlight>
 
The library function <code>listToMaybe</code> gets at most one element from its list argument. The last variant can be written as the optimal
 
<langsyntaxhighlight lang="haskell">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</langsyntaxhighlight>
 
See [[Sieve of Eratosthenes]] or [[Primality by trial division]] for a source of primes to use with this function.
Line 2,570:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
factors := primedecomp(2^43-1) # a big int
end
Line 2,587:
end
 
link factors</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}} [http://www.cs.arizona.edu/icon/library/src/procs/factors.icn Uses genfactors and prime from factors]
Line 2,595:
 
=={{header|J}}==
<syntaxhighlight lang ="j">q:</langsyntaxhighlight>
 
{{out|Example use}}
<langsyntaxhighlight lang="j"> q: 3684
2 2 3 307</langsyntaxhighlight>
 
and, more elaborately:
 
<langsyntaxhighlight lang="j"> _1+2^128x
340282366920938463463374607431768211455
q: _1+2^128x
3 5 17 257 641 65537 274177 6700417 67280421310721
*/ q: _1+2^128x
340282366920938463463374607431768211455</langsyntaxhighlight>
 
=={{header|Java}}==
Line 2,614:
This is a version for arbitrary-precision integers
which assumes the existence of a function with the signature:
<langsyntaxhighlight lang="java">public boolean prime(BigInteger i);</langsyntaxhighlight>
You will need to import java.util.List, java.util.LinkedList, and java.math.BigInteger.
<langsyntaxhighlight lang="java">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
Line 2,627:
}
return ans;
}</langsyntaxhighlight>
 
Alternate version, optimised to be faster.
<langsyntaxhighlight lang="java">private static final BigInteger two = BigInteger.valueOf(2);
 
public List<BigInteger> primeDecomp(BigInteger a) {
Line 2,661:
}
return result;
}</langsyntaxhighlight>
 
Another alternate version designed to make fewer modular calculations:
<langsyntaxhighlight lang="java">
private static final BigInteger TWO = BigInteger.valueOf(2);
private static final BigInteger THREE = BigInteger.valueOf(3);
Line 2,708:
return factors;
}
</syntaxhighlight>
</lang>
{{trans|C#}}
Simple but very inefficient method,
because it will test divisibility of all numbers from 2 to max prime factor.
When decomposing a large prime number this will take O(n) trial divisions instead of more common O(log n).
<langsyntaxhighlight lang="java">public static List<BigInteger> primeFactorBig(BigInteger a){
List<BigInteger> ans = new LinkedList<BigInteger>();
 
Line 2,723:
}
return ans;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
This code uses the BigInteger Library [http://xenon.stanford.edu/~tjw/jsbn/jsbn.js jsbn] and [http://xenon.stanford.edu/~tjw/jsbn/jsbn2.js jsbn2]
<langsyntaxhighlight lang="javascript">function run_factorize(input, output) {
var n = new BigInteger(input.value, 10);
var TWO = new BigInteger("2", 10);
Line 2,765:
divisor = divisor.add(TWO);
}
}</langsyntaxhighlight>
 
Without any library.
<langsyntaxhighlight lang="javascript">function run_factorize(n) {
if (n <= 3)
return [n];
Line 2,807:
ans.push(n);
return ans;
}</langsyntaxhighlight>
 
TDD using Jasmine
 
PrimeFactors.js
<langsyntaxhighlight lang="javascript">function factors(n) {
if (!n || n < 2)
return [];
Line 2,826:
return f;
};
</syntaxhighlight>
</lang>
 
SpecPrimeFactors.js (with tag for Chutzpah)
<langsyntaxhighlight lang="javascript">/// <reference path="PrimeFactors.js" />
 
describe("Prime Factors", function() {
Line 2,877:
});
});
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 2,897:
reliable for integers up to and including 9,007,199,254,740,992 (2^53). However, "factors"
could be easily modified to work with a "BigInt" library for jq, such as [https://gist.github.com/pkoppstein/d06a123f30c033195841 BigInt.jq].
<langsyntaxhighlight lang="jq">def factors:
. as $in
| [2, $in, false]
Line 2,910:
end
end )
| if .[2] then .[0] else empty end ;</langsyntaxhighlight>
'''Examples''':
<syntaxhighlight lang="jq">
<lang jq>
24 | factors
#=> 2 2 2 3
Line 2,921:
# 2**29-1 is 536870911
[ 536870911 | factors ]
#=> [233,1103,2089]</langsyntaxhighlight>
 
=={{header|Julia}}==
using package Primes.jl:
<langsyntaxhighlight lang="julia">
julia> Pkg.add("Primes")
julia> factor(8796093022207)
[9719=>1,431=>1,2099863=>1]
</syntaxhighlight>
</lang>
(The <code>factor</code> function returns a dictionary
whose keys are the factors and whose values are the multiplicity of each factor.)
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.math.BigInteger
Line 2,968:
println("2^${"%2d".format(prime)} - 1 = ${bigPow2.toString().padEnd(30)} => ${getPrimeFactors(bigPow2)}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,000:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def prime_fact.smallest
{def prime_fact.smallest.r
Line 3,032:
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]
</syntaxhighlight>
</lang>
 
=={{header|LFE}}==
 
<langsyntaxhighlight lang="lisp">
(defun factors (n)
(factors n 2 '()))
Line 3,047:
((n k acc)
(factors n (+ k 1) acc)))
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">-- 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).
Line 3,072:
f.add(n)
return f
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">put getPrimeFactors(12)
-- [2.0000, 2.0000, 3.0000]
 
Line 3,083:
 
put getPrimeFactors(1125899906842623.0)
-- [3, 251, 601, 4051, 614141]</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">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</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 3,096:
is located at [[Primality by trial division#Lua]]
 
<langsyntaxhighlight lang="lua">function PrimeDecomposition( n )
local f = {}
Line 3,117:
return f
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Prime_decomposition {
Inventory Known1=2@, 3@
Line 3,171:
}
Prime_decomposition
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
Line 3,179:
of prime factors and their multiplicities:
 
<langsyntaxhighlight Maplelang="maple">> ifactor(1337);
(7) (191)
</syntaxhighlight>
</lang>
<langsyntaxhighlight Maplelang="maple">> ifactors(1337);
[1, [[7, 1], [191, 1]]]
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Bare built-in function does:
<langsyntaxhighlight Mathematicalang="mathematica"> FactorInteger[2016] => {{2, 5}, {3, 2}, {7, 1}}</langsyntaxhighlight>
 
Read as: 2 to the power 5 times 3 squared times 7 (to the power 1).
To show them nicely we could use the following functions:
<langsyntaxhighlight Mathematicalang="mathematica">supscript[x_,y_]:=If[y==1,x,Superscript[x,y]]
ShowPrimeDecomposition[input_Integer]:=Print@@{input," = ",Sequence@@Riffle[supscript@@@FactorInteger[input]," "]}</langsyntaxhighlight>
 
Example for small prime:
<syntaxhighlight lang Mathematica="mathematica"> ShowPrimeDecomposition[1337]</langsyntaxhighlight>
gives:
<langsyntaxhighlight Mathematicalang="mathematica"> 1337 = 7 191</langsyntaxhighlight>
 
Examples for large primes:
<langsyntaxhighlight Mathematicalang="mathematica"> Table[AbsoluteTiming[ShowPrimeDecomposition[2^a-1]]//Print[#[[1]]," sec"]&,{a,50,150,10}];</langsyntaxhighlight>
gives back:
<langsyntaxhighlight Mathematicalang="mathematica">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
Line 3,224:
0.009419 sec
1427247692705959881058285969449495136382746623 = 3^2 7 11 31 151 251 331 601 1801 4051 100801 10567201 1133836730401
0.007705 sec</langsyntaxhighlight>
 
=={{header|MATLAB}}==
<langsyntaxhighlight Matlablang="matlab">function [outputPrimeDecomposition] = primedecomposition(inputValue)
outputPrimeDecomposition = factor(inputValue);</langsyntaxhighlight>
 
=={{header|Maxima}}==
Using the built-in function:
<langsyntaxhighlight lang="maxima">(%i1) display2d: false$ /* disable rendering exponents as superscripts */
(%i2) factor(2016);
(%o2) 2^5*3^2*7
</syntaxhighlight>
</lang>
Using the underlying language:
<langsyntaxhighlight lang="maxima">prime_dec(n) := flatten(create_list(makelist(first(a), second(a)), a, ifactors(n)))$
 
/* or, slighlty more "functional" */
Line 3,243:
 
prime_dec(2^4*3^5*5*7^2);
/* [2, 2, 2, 2, 3, 3, 3, 3, 3, 5, 7, 7] */</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">ERATO1(HI)
SET HI=HI\1
KILL ERATO1 ;Don't make it new - we want it to remain after the quit
Line 3,267:
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</langsyntaxhighlight>
{{out|Usage}}
<pre>USER>K ERATO1,PRIMDECO D PRIMDECO^ROSETTA(31415) W PRIMDECO
Line 3,284:
=={{header|Nim}}==
Based on python floating point solution, but using integers rather than floats.
<langsyntaxhighlight lang="nim">import math, sequtils, strformat, strutils, times
 
proc getStep(n: int64): int64 {.inline.} =
Line 3,321:
let start = cpuTime()
stdout.write primeFac(p).join(", ")
echo &" => {(1000 * (cpuTime() - start)).toInt} ms"</langsyntaxhighlight>
 
{{out}}
Line 3,344:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">open Big_int;;
 
let prime_decomposition x =
Line 3,355:
inner (succ_big_int c) p
in
inner (succ_big_int (succ_big_int zero_big_int)) x;;</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">r = factor(120202039393)</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 3,364:
Oforth handles aribitrary precision integers.
 
<langsyntaxhighlight Oforthlang="oforth">: factors(n) // ( aInteger -- aList )
| k p |
ListBuffer new
Line 3,377:
]
n 1 > ifTrue: [ n over add ]
dup freeze ;</langsyntaxhighlight>
 
{{out}}
Line 3,393:
Thus <code>factor(12)==[2,2;3,1]</code> is true.
But it's simple enough to convert this to a vector with repetition:
<langsyntaxhighlight lang="parigp">pd(n)={
my(f=factor(n),v=f[,1]~);
for(i=1,#v,
Line 3,401:
);
vecsort(v)
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program PrimeDecomposition(output);
 
type
Line 3,441:
for j := low(factors) to high(factors) do
writeln (factors[j]);
end.</langsyntaxhighlight>
{{out}}
<pre>% ./PrimeDecomposition
Line 3,460:
'''Optimization:'''
 
<langsyntaxhighlight lang="pascal">Program PrimeDecomposition(output);
 
type
Line 3,505:
writeln (factors[j]);
readln;
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 3,512:
 
===Trivial trial division (very slow)===
<langsyntaxhighlight lang="perl">sub prime_factors {
my ($n, $d, @out) = (shift, 1);
while ($n > 1 && $d++) {
Line 3,520:
}
 
print "@{[prime_factors(1001)]}\n";</langsyntaxhighlight>
 
===Better trial division===
This is ''much'' faster than the trivial version above.
<langsyntaxhighlight lang="perl">sub prime_factors {
my($n, $p, @out) = (shift, 3);
return if $n < 1;
Line 3,537:
push @out, $n if $n > 1;
@out;
}</langsyntaxhighlight>
 
===Modules===
Line 3,543:
These both take about 1 second to factor all Mersenne numbers from M_1 to M_150.
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/factor forprimes/;
use bigint;
 
Line 3,549:
my $p = 2 ** $_ - 1;
print "2**$_-1: ", join(" ", factor($p)), "\n";
} 100, 150;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,565:
 
{{libheader|Math::Pari}}
<langsyntaxhighlight lang="perl">use Math::Pari qw/:int factorint isprime/;
 
# Convert Math::Pari's format into simple vector
Line 3,577:
my $p = 2 ** $_ - 1;
print "2^$_-1: ", join(" ", factor($p)), "\n";
}</langsyntaxhighlight>
With the same output.
 
Line 3,583:
For small numbers less than 2<small><sup>53</sup></small> on 32bit and 2<small><sup>64</sup></small> on 64bit just use prime_factors().
{{libheader|Phix/mpfr}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.0"</span><span style="color: #0000FF;">)</span>
Line 3,605:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,639:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
% Checking 2**prime-1
foreach(P in primes(60))
Line 3,677:
Divisors := Divisors ++ [Div],
M := M div Div
end.</langsyntaxhighlight>
 
{{out}}
Line 3,704:
17 19 23 29 31 37 ..), as described by Donald E. Knuth, "The Art of Computer
Programming", Vol.2, p.365.
<langsyntaxhighlight PicoLisplang="picolisp">(de factor (N)
(make
(let (D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .)) M (sqrt N))
Line 3,713:
(link N) ) ) )
 
(factor 1361129467683753853853498429727072845823)</langsyntaxhighlight>
{{out}}
<pre>-> (3 11 31 131 2731 8191 409891 7623851 145295143558111)</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">
test: procedure options (main, reorder);
declare (n, i) fixed binary (31);
Line 3,756:
 
end test;
</syntaxhighlight>
</lang>
{{out|Results from various runs}}
<pre>
Line 3,769:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function eratosthenes ($n) {
if($n -gt 1){
Line 3,802:
"$(prime-decomposition 12)"
"$(prime-decomposition 100)"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 3,810:
 
=={{header|Prolog}}==
<langsyntaxhighlight Prologlang="prolog">prime_decomp(N, L) :-
SN is sqrt(N),
prime_decomp_1(N, SN, 2, [], L).
Line 3,846:
prime_decomp_2(N, SN, D1, L, LF)
)
).</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight Prologlang="prolog"> ?- time(prime_decomp(9007199254740991, L)).
% 138,882 inferences, 0.344 CPU in 0.357 seconds (96% CPU, 404020 Lips)
L = [20394401,69431,6361].
Line 3,859:
?- 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].</langsyntaxhighlight>
 
====Simple version====
Line 3,865:
Optimized to stop on square root, and count by +2 on odds, above 2.
 
<langsyntaxhighlight Prologlang="prolog">factors( N, FS):-
factors2( N, FS).
Line 3,880:
; 0 is N rem K -> FS = [K|FS2], N2 is N div K, factors( N2, K, FS2)
; K2 is K+2, factors( N, K2, FS)
).</langsyntaxhighlight>
 
====Expression Tree version====
Uses a 2*3*5*7 factor wheel, but the main feature is that it returns the decomposition as a fully simplified expression tree.
<syntaxhighlight lang="prolog">
<lang Prolog>
wheel2357(L) :-
W = [2, 4, 2, 4, 6, 2, 6, 4,
Line 3,920:
reverse_factors(A*B, C*A) :- reverse_factors(B, C), !.
reverse_factors(A, A).
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,943:
 
=={{header|Pure}}==
<langsyntaxhighlight lang="pure">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;</langsyntaxhighlight>
 
=={{header|PureBasic}}==
{{works with|PureBasic|4.41}}
<syntaxhighlight lang="purebasic">
<lang PureBasic>
CompilerIf #PB_Compiler_Debugger
CompilerError "Turn off the debugger if you want reasonable speed in this example."
Line 3,986:
S + #CRLF$ + Str(Factors())
Next
MessageRequester("", S)</langsyntaxhighlight>
{{out}}
<pre>Factored 9007199254740991 in 0.27 seconds.
Line 3,998:
Note: the program below is saved to file <code>prime_decomposition.py</code> and imported as a library [[Least_common_multiple#Python|here]], [[Semiprime#Python|here]], [[Almost_prime#Python|here]], [[Emirp primes#Python|here]] and [[Extensible_prime_generator#Python|here]].
 
<langsyntaxhighlight lang="python">from __future__ import print_function
 
import sys
Line 4,085:
print( "=> {0:.2f}s".format( time.time()-start ) )
if m >= 59:
break</langsyntaxhighlight>
{{out}}
<pre>2**2-1 = 3, with factors:
Line 4,125:
Here a shorter and marginally faster algorithm:
 
<langsyntaxhighlight lang="python">from math import floor, sqrt
try:
long
Line 4,146:
tocalc = 2**59-1
print("%s = %s" % (tocalc, fac(tocalc)))
print("Needed %ss" % (time.time() - start))</langsyntaxhighlight>
 
{{out}}
Line 4,154:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ [] swap
dup times
[ [ dup i^ 2 + /mod
Line 4,165:
drop ] is primefactors ( n --> [ )
 
1047552 primefactors echo</langsyntaxhighlight>
 
{{out}}
Line 4,172:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">findfactors <- function(num) {
x <- NULL
firstprime<- 2; secondprime <- 3; everyprime <- num
Line 4,186:
}
 
print(findfactors(1027*4))</langsyntaxhighlight>
 
Or a more explicit (but less efficient) recursive approach:
 
===Recursive Approach (Less efficient for large numbers)===
<syntaxhighlight lang="r">
<lang R>
primes <- as.integer(c())
 
Line 4,227:
}
}
</syntaxhighlight>
</lang>
=== Alternate solution ===
<langsyntaxhighlight Rlang="r">findfactors <- function(n) {
a <- NULL
if (n > 1) {
Line 4,247:
}
a
}</langsyntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(require math)
(define (factors n)
(append-map (λ (x) (make-list (cadr x) (car x))) (factorize n)))
</syntaxhighlight>
</lang>
 
Or, an explicit (and less efficient) computation:
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define (factors number)
Line 4,266:
(let-values ([(q r) (quotient/remainder n i)])
(if (zero? r) (cons i (loop q i)) (loop n (add1 i)))))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 4,273:
This is a pure Raku version that uses no outside libraries. It uses a variant of Pollard's rho factoring algorithm and is fairly performent when factoring numbers < 2⁸⁰; typically taking well under a second on an i7. It starts to slow down with larger numbers, but really bogs down factoring numbers that have more than 1 factor larger than about 2⁴⁰.
 
<syntaxhighlight lang="raku" perl6line>sub prime-factors ( Int $n where * > 0 ) {
return $n if $n.is-prime;
return () if $n == 1;
Line 4,309:
"factors of $n: ",
prime-factors($n).join(' × '), " \t in ", (now - $start).fmt("%0.3f"), " sec."
}</langsyntaxhighlight>
 
{{out}}
Line 4,325:
===External library===
If you really need a speed boost, load the highly optimized Perl 5 ntheory module. It needs a little extra plumbing to deal with the lack of built-in big integer support, but for large number factoring the interface overhead is worth it.
<syntaxhighlight lang="raku" perl6line>use Inline::Perl5;
my $p5 = Inline::Perl5.new();
$p5.use( 'ntheory' );
Line 4,340:
say "factors of $n: ",
prime-factors($n).join(' × '), " \t in ", (now - $start).fmt("%0.3f"), " sec."
}</langsyntaxhighlight>
{{out}}
<pre>factors of 536870911: 233 × 1103 × 2089 in 0.001 sec.
Line 4,366:
Since the majority of computing time is spent looking for primes, that part of the program was
<br>optimized somewhat (but could be extended if more optimization is wanted).
<langsyntaxhighlight lang="rexx">/*REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/
numeric digits 1000 /*handle thousand digits for the powers*/
parse arg bot top step base add /*get optional arguments from the C.L. */
Line 4,408:
/* [↓] The $ list has a leading blank.*/
if x==1 then return $ /*Is residual=unity? Then don't append.*/
return $ x /*return $ with appended residual. */</langsyntaxhighlight>
'''output''' &nbsp; when using the default input of: &nbsp; <tt> 1 &nbsp; 100 </tt>
 
Line 4,655:
===optimized more===
This REXX version is about &nbsp; '''20%''' &nbsp; faster than the 1<sup>st</sup> REXX version when factoring one million numbers.
<langsyntaxhighlight lang="rexx">/*REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/
numeric digits 1000 /*handle thousand digits for the powers*/
parse arg bot top step base add /*get optional arguments from the C.L. */
Line 4,702:
/* [↓] The $ list has a leading blank.*/
if x==1 then return $ /*Is residual=unity? Then don't append.*/
return $ x /*return $ with appended residual. */</langsyntaxhighlight>
'''output''' &nbsp; is identical to the 1<sup>st</sup> REXX version. <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
prime = 18705
decomp(prime)
Line 4,727:
next
return 1
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
===Built in===
<langsyntaxhighlight lang="ruby">irb(main):001:0> require 'prime'
=> true
irb(main):003:0> 2543821448263974486045199.prime_division
=> [[701, 1], [1123, 2], [2411, 1], [1092461, 2]]</langsyntaxhighlight>
 
===Simple algorithm===
<langsyntaxhighlight lang="ruby"># Get prime decomposition of integer _i_.
# This routine is terribly inefficient, but elegance rules.
def prime_factors(i)
Line 4,749:
factors = prime_factors(2**i-1)
puts "2**#{i}-1 = #{2**i-1} = #{factors.join(' * ')}"
end</langsyntaxhighlight>
{{out}}
<pre>...
Line 4,758:
 
===Faster algorithm===
<langsyntaxhighlight lang="ruby"># 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.
Line 4,789:
factors = prime_factors_faster(2**i-1)
puts "2**#{i}-1 = #{2**i-1} = #{factors.join(' * ')}"
end</langsyntaxhighlight>
{{out}}
<pre>...
Line 4,799:
This benchmark compares the different implementations.
 
<langsyntaxhighlight lang="ruby">require 'benchmark'
require 'mathn'
Benchmark.bm(24) do |x|
Line 4,808:
x.report(" Integer#prime_division") { i.prime_division }
end
end</langsyntaxhighlight>
 
With [[MRI]] 1.8, ''prime_factors'' is slow, ''Integer#prime_division'' is fast, and ''prime_factors_faster'' is very fast. With MRI 1.9, Integer#prime_division is also very fast.
Line 4,830:
The implementation:
 
<langsyntaxhighlight Rustlang="rust">use num_bigint::BigUint;
use num_traits::{One, Zero};
use std::fmt::{Display, Formatter};
Line 4,922:
}
}
</syntaxhighlight>
</lang>
 
=={{header|S-BASIC}}==
<syntaxhighlight lang="s-basic">
<lang S-BASIC>
rem - return p mod q
function mod(p, q = integer) = integer
Line 4,969:
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,988:
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">import annotation.tailrec
import collection.parallel.mutable.ParSeq
 
Line 5,030:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,053:
Since the problems seems to ask for it, here is one version that does it:
 
<langsyntaxhighlight Scalalang="scala">class PrimeFactors(n: BigInt) extends Iterator[BigInt] {
val zero = BigInt(0)
val one = BigInt(1)
Line 5,085:
 
def hasNext = currentN != one && currentN > zero
}</langsyntaxhighlight>
 
The method isProbablePrime(n) has a chance of 1 - 1/(2^n) of correctly
Line 5,091:
Next is a version that does not depend on identifying primes,
and works with arbitrary integral numbers:
<langsyntaxhighlight Scalalang="scala">class PrimeFactors[N](n: N)(implicit num: Integral[N]) extends Iterator[N] {
import num._
val two = one + one
Line 5,115:
 
def hasNext = currentN != one && currentN > zero
}</langsyntaxhighlight>
{{out}}
Both versions can be rather slow, as they accept arbitrarily big numbers,
Line 5,144:
 
Alternatively, Scala LazyLists and Iterators support quite elegant one-line encodings of iterative/recursive algorithms, allowing us to to define the prime factorization like so:
<langsyntaxhighlight lang="scala">import spire.math.SafeLong
import spire.implicits._
def pFactors(num: SafeLong): Vector[SafeLong] = Iterator.iterate((Vector[SafeLong](), num, SafeLong(2))){case (ac, n, f) => if(n%f == 0) (ac :+ f, n/f, f) else (ac, n, f + 1)}.dropWhile(_._2 != 1).next._1</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (factor number)
(define (*factor divisor number)
(if (> (* divisor divisor) number)
Line 5,159:
 
(display (factor 111111111111))
(newline)</langsyntaxhighlight>
{{out}}
(3 7 11 13 37 101 9901)
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const func array integer: factorise (in var integer: number) is func
result
var array integer: result is 0 times 0;
Line 5,181:
result &:= [](number);
end if;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#factorise]
Line 5,188:
'''Recursive Using isPrime'''
 
<langsyntaxhighlight lang="sequencel">isPrime(n) := n = 2 or (n > 1 and none(n mod ([2]++((1...floor(sqrt(n)/2))*2+1)) = 0));
 
primeFactorization(num) := primeFactorizationHelp(num, []);
Line 5,198:
current when size(primeFactors) = 0
else
primeFactorizationHelp(num / product(primeFactors), current ++ primeFactors);</langsyntaxhighlight>
 
Using isPrime Based On: [https://www.youtube.com/watch?v=CsCBkPg1FbE]
Line 5,204:
'''Recursive Trial Division'''
 
<langsyntaxhighlight lang="sequencel">primeFactorization(num) := primeFactorizationHelp(num, 2, []);
 
primeFactorizationHelp(num, divisor, factors(1)) :=
Line 5,211:
primeFactorizationHelp(num, divisor + 1, factors) when num mod divisor /= 0
else
primeFactorizationHelp(num / divisor, divisor, factors ++ [divisor]);</langsyntaxhighlight>
 
=={{header|Sidef}}==
Built-in:
<langsyntaxhighlight lang="ruby">say factor(536870911) #=> [233, 1103, 2089]
say factor_exp(536870911) #=> [[233, 1], [1103, 1], [2089, 1]]</langsyntaxhighlight>
 
Trial division:
<langsyntaxhighlight lang="ruby">func prime_factors(n) {
return [] if (n < 1)
gather {
Line 5,236:
take(n) if (n > 1)
}
}</langsyntaxhighlight>
 
Calling the function:
<langsyntaxhighlight lang="ruby">say prime_factors(536870911) #=> [233, 1103, 2089]</langsyntaxhighlight>
 
=={{header|Simula}}==
Simula has no built-in function to test for prime numbers.<br>
Code for class bignum can be found here: https://rosettacode.org/wiki/Pi#Simula
<langsyntaxhighlight lang="simula">
EXTERNAL CLASS BIGNUM;
BIGNUM
Line 5,325:
 
END;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,338:
=={{header|Slate}}==
Admittedly, this is just based on the Smalltalk entry below:
<langsyntaxhighlight lang="slate">n@(Integer traits) primesDo: block
"Decomposes the Integer into primes, applying the block to each (in increasing
order)."
Line 5,352:
[div: next.
next: next + 2] "Just look at the next odd integer."
].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
 
<langsyntaxhighlight lang="smalltalk">Integer extend [
primesDo: aBlock [
| div next rest |
Line 5,369:
]
]
123456 primesDo: [ :each | each printNl ]</langsyntaxhighlight>
 
=={{header|SPAD}}==
{{works with|FriCAS, OpenAxiom, Axiom}}
<syntaxhighlight lang="spad">
<lang SPAD>
 
(1) -> factor 102400
Line 5,385:
Type: Factored(Integer)
 
</syntaxhighlight>
</lang>
 
Domain:[http://fricas.github.io/api/Factored.html?highlight=factor Factored(R)]
Line 5,391:
=={{header|Standard ML}}==
Trial division
<syntaxhighlight lang="sml">
<lang SML>
val factor = fn n :IntInf.int =>
let
Line 5,413:
 
end;
</syntaxhighlight>
</lang>
<pre>
- Array.fromList(factor 122489234920000001278234798233);;
Line 5,423:
The following Mata function will factor any representable positive integer (that is, between 1 and 2^53).
 
<langsyntaxhighlight lang="stata">function factor(n_) {
n = n_
a = J(0,2,.)
Line 5,448:
return(a)
}
}</langsyntaxhighlight>
 
=={{header|Swift}}==
Line 5,455:
Uses the sieve of Eratosthenes. This is generic on any type that conforms to BinaryInteger. So in theory any BigInteger library should work with it.
 
<langsyntaxhighlight lang="swift">func primeDecomposition<T: BinaryInteger>(of n: T) -> [T] {
guard n > 2 else { return [] }
 
Line 5,479:
 
print("2^\(prime) - 1 = \(m) => \(decom)")
}</langsyntaxhighlight>
 
{{out}}
Line 5,501:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc factors {x} {
# list the prime factors of x in ascending order
set result [list]
Line 5,517:
return $result
}
</syntaxhighlight>
</lang>
Testing
<langsyntaxhighlight lang="tcl">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 primes [factors $n]} 1} tm
puts [format "2**%02d-1 = %-18s = %-22s => %s" $m $n [join $primes *] $tm]
}</langsyntaxhighlight>
{{out}}
<pre>2**02-1 = 3 = 3 => 184 microseconds per iteration
Line 5,544:
 
=={{header|TI-83 BASIC}}==
<langsyntaxhighlight lang="ti83b">::prgmPREMIER
Disp "FACTEURS PREMIER"
Prompt N
Line 5,593:
sub(Str0,4,O-3)→Str0
ClrList L5,L6
DelVar Y�</langsyntaxhighlight>
{{out}}
<pre>
Line 5,605:
 
=={{Header|Tiny BASIC}}==
<langsyntaxhighlight Tinylang="tiny BASICbasic">10 PRINT "Enter a number."
20 INPUT N
25 PRINT "------"
Line 5,619:
300 LET N = N / I
310 PRINT I
320 GOTO 50</langsyntaxhighlight>
{{out}}
<pre>
Line 5,652:
{{trans|Common Lisp}}
 
<langsyntaxhighlight lang="txr">@(next :args)
@(do
(defun factor (n)
Line 5,667:
@(output)
@num -> {@(rep)@factors, @(last)@factors@(end)}
@(end)</langsyntaxhighlight>
{{out}}
<pre>$ txr factor.txr 1139423842450982345
Line 5,690:
=={{header|V}}==
like in scheme (using variables)
<langsyntaxhighlight lang="v">[prime-decomposition
[inner [c p] let
[c c * p >]
Line 5,699:
ifte]
ifte].
2 swap inner].</langsyntaxhighlight>
 
(mostly) the same thing using stack (with out variables)
<langsyntaxhighlight lang="v">[prime-decomposition
[inner
[dup * <]
Line 5,711:
ifte]
ifte].
2 inner].</langsyntaxhighlight>
 
Using it
<syntaxhighlight lang ="v">|1221 prime-decomposition puts</langsyntaxhighlight>
=[3 11 37]
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">Function PrimeFactors(n)
arrP = Split(ListPrimes(n)," ")
divnum = n
Line 5,760:
 
WScript.StdOut.Write PrimeFactors(CInt(WScript.Arguments(0)))
WScript.StdOut.WriteLine</langsyntaxhighlight>
 
{{out}}
Line 5,775:
{{libheader|Wren-fmt}}
The examples are borrowed from the Go solution.
<langsyntaxhighlight lang="ecmascript">import "/big" for BigInt
import "/fmt" for Fmt
 
Line 5,781:
for (val in vals) {
Fmt.print("$10d -> $n", val, BigInt.primeFactors(val))
}</langsyntaxhighlight>
 
{{out}}
Line 5,794:
=={{header|XSLT}}==
Let's assume that in XSLT the application of a template is similar to the invocation of a function. So when the following template
<langsyntaxhighlight lang="xml"><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
 
<xsl:template match="/numbers">
Line 5,866:
</xsl:template>
 
</xsl:stylesheet></langsyntaxhighlight>
is applied against the document
<langsyntaxhighlight lang="xml"><numbers>
<number><value>1</value></number>
<number><value>2</value></number>
Line 5,875:
<number><value>9</value></number>
<number><value>255</value></number>
</numbers></langsyntaxhighlight>
then the output contains the prime decomposition of each number:
<langsyntaxhighlight lang="html"><html>
<body>
<ul>
Line 5,919:
</ul>
</body>
</html></langsyntaxhighlight>
 
=={{header|zkl}}==
With 64 bit ints:
<langsyntaxhighlight lang="zkl">fcn primeFactors(n){ // Return a list of factors of n
acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum
if(n==1 or k>maxD) acc.close();
Line 5,935:
if(n!=m) acc.append(n/m); // opps, missed last factor
else acc;
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach n in (T(5,12, 2147483648, 2199023255551, 8796093022207,
9007199254740991, 576460752303423487)){
println(n,": ",primeFactors(n).concat(", "))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,951:
</pre>
Unfortunately, big ints (GMP) don't have (quite) the same interface as ints (since there is no big float, BI.toFloat() truncates to a double so BI.toFloat().sqrt() is wrong). So mostly duplicate code is needed:
<langsyntaxhighlight lang="zkl">fcn factorsBI(n){ // Return a list of factors of n
acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum
if(n==1 or k>maxD) acc.close();
Line 5,963:
if(n!=m) acc.append(n/m); // opps, missed last factor
else acc;
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">var BN=Import("zklBigNum");
foreach n in (T(BN("12"),
BN("340282366920938463463374607431768211455"))){
println(n,": ",factorsBI(n).concat(", "))
}</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits