Factors of a Mersenne number: Difference between revisions

→‎{{header|jq}}: no need for call to reverse
(→‎{{header|Haskell}}: upd dead link to live one via web.archive.org)
(→‎{{header|jq}}: no need for call to reverse)
 
(77 intermediate revisions by 31 users not shown)
Line 21:
Use the result of the modulo from the last step as the initial value of <tt>square</tt> in the next step:
 
Remove remove Optional optional
square square top bit multiply by 2 mod 47
──────────── ─────── ───────────── ──────
------------ ------- ------------- ------
1*1 = 1 1 0111 1*2 = 2 2
2*2 = 4 0 111 no 4
4*4 = 16 1 11 16*2 = 32 32
32*32 = 1024 1 1 1024*2 = 2048 27
27*27 = 729 1 729*2 = 1458 1
 
Since 2<sup>23</sup> mod 47 = 1, 47 is a factor of 2<sup>P</sup>-1.
Line 44:
Using the above method find a factor of 2<sup>929</sup>-1 (aka M929)
 
 
;See also:
;Related tasks:
* [https://www.youtube.com/watch?v=SNwvJ7psoow Computers in 1948: 2¹²⁷-1]<br>
* &nbsp; [[count in factors]]
* &nbsp; [[prime decomposition]]
* &nbsp; [[factors of an integer]]
* &nbsp; [[Sieve of Eratosthenes]]
* &nbsp; [[primality by trial division]]
* &nbsp; [[trial factoring of a Mersenne number]]
* &nbsp; [[partition an integer X into N primes]]
* &nbsp; [[sequence of primes by Trial Division]]
 
 
;See also:
* &nbsp; [https://www.youtube.com/watch?v=SNwvJ7psoow Computers in 1948: 2<sup>127</sup> - 1] <br> &nbsp; &nbsp; &nbsp; (Note: &nbsp; This video is no longer available because the YouTube account associated with this video has been terminated.)
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F is_prime(a)
I a == 2 {R 1B}
I a < 2 | a % 2 == 0 {R 0B}
L(i) (3 .. Int(sqrt(a))).step(2)
I a % i == 0
R 0B
R 1B
 
F m_factor(p)
V max_k = 16384 I/ p
L(k) 0 .< max_k
V q = 2 * p * k + 1
I !is_prime(q)
L.continue
E I q % 8 != 1 & q % 8 != 7
L.continue
E I pow(2, p, q) == 1
R q
R 0
 
V exponent = Int(input(‘Enter exponent of Mersenne number: ’))
I !is_prime(exponent)
print(‘Exponent is not prime: #.’.format(exponent))
E
V factor = m_factor(exponent)
I factor == 0
print(‘No factor found for M#.’.format(exponent))
E
print(‘M#. has a factor: #.’.format(exponent, factor))</syntaxhighlight>
 
{{out}}
<pre>
Enter exponent of Mersenne number: 929
M929 has a factor: 13007
</pre>
 
=={{header|8086 Assembly}}==
 
<syntaxhighlight lang="asm">P: equ 929 ; P for 2^P-1
cpu 8086
bits 16
org 100h
section .text
mov ax,P ; Is P prime?
call prime
mov dx,notprm
jc msg ; If not, say so and stop.
xor bp,bp ; Let BP hold k
test_k: inc bp ; k += 1
mov ax,P ; Calculate 2kP + 1
mul bp ; AX = kP
shl ax,1 ; AX = 2kP
inc ax ; AX = 2kP + 1
mov dx,ovfl ; If AX overflows (16 bits), say so and stop
jc msg
mov bx,ax ; What is 2^P mod (2kP+1)?
mov cx,P
call modpow
dec ax ; If it is 1, we're done
jnz test_k ; If not, increment K and try again
mov dx,factor ; If so, we found a factor
call msg
prbx: mov ax,10 ; The factor is still in BX
xchg bx,ax ; Put factor in AX and divisor (10) in BX
mov di,number ; Generate ASCII representation of number
digit: xor dx,dx
div bx ; Divide current number by 10,
add dl,'0' ; add '0' to remainder,
dec di ; move pointer back,
mov [di],dl ; store digit,
test ax,ax ; and if there are more digits,
jnz digit ; find the next digit.
mov dx,di ; Finally, print the number.
jmp msg
;;; Calculate 2^CX mod BX
;;; Output: AX
;;; Destroyed: CX, DX
modpow: shl cx,1 ; Shift CX left until top bit in high bit
jnc modpow ; Keep shifting while carry zero
rcr cx,1 ; Put the top bit back into CX
mov ax,1 ; Start with square = 1
.step: mul ax ; Square (result is 32-bit, goes in DX:AX)
shl cx,1 ; Grab a bit from CX
jnc .nodbl ; If zero, don't multiply by two
shl ax,1 ; Shift DX:AX left (mul by two)
rcl dx,1
.nodbl: div bx ; Divide DX:AX by BX (putting modulus in DX)
mov ax,dx ; Continue with modulus
jcxz .done ; When CX reaches 0, we're done
jmp .step ; Otherwise, do the next step
.done: ret
;;; Is AX prime?
;;; Output: carry clear if prime, set if not prime.
;;; Destroyed: AX, BX, CX, DX, SI, DI, BP
prime: mov cx,[prcnt] ; See if AX is already in the list of primes
mov di,primes
repne scasw ; If so, return
je modpow.done ; Reuse the RET just above here (carry clear)
mov bp,ax ; Move AX out of the way
mov bx,[di-2] ; Start generating new primes
.sieve: inc bx ; BX = last prime + 2
inc bx
cmp bp,bx ; If BX higher than number to test,
jb modpow.done ; stop, number is not prime. (carry set)
mov cx,[prcnt] ; CX = amount of current primes
mov si,primes ; SI = start of primes
.try: mov ax,bx ; BX divisible by current prime?
xor dx,dx
div word [si]
test dx,dx ; If so, BX is not prime.
jz .sieve
inc si
inc si
loop .try ; Otherwise, try next prime.
mov ax,bx ; If we get here, BX _is_ prime
stosw ; So add it to the list
inc word [prcnt] ; We have one more prime
cmp ax,bp ; Is it the prime we are looking for?
jne .sieve ; If not, try next prime
ret
;;; Print message in DX
msg: mov ah,9
int 21h
ret
section .data
db "*****" ; Placeholder for number
number: db "$"
notprm: db "P is not prime.$"
ovfl: db "Range of factor exceeded (max 16 bits)."
factor: db "Found factor: $"
prcnt: dw 2 ; Amount of primes currently in list
primes: dw 2, 3 ; List of primes to be extended</syntaxhighlight>
 
{{out}}
 
<pre>Found factor: 13007</pre>
 
=={{header|360 Assembly}}==
Line 52 ⟶ 204:
Use of bitwise operations
(TM (Test under Mask), SLA (Shift Left Arithmetic),SRA (Shift Right Arithmetic)).
<syntaxhighlight lang="text">* Factors of a Mersenne number 11/09/2015
MERSENNE CSECT
USING MERSENNE,R15
Line 141 ⟶ 293:
PG DS CL24 buffer
YREGS
END MERSENNE</langsyntaxhighlight>
{{out}}
<pre>
Line 149 ⟶ 301:
=={{header|Ada}}==
mersenne.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
-- reuse Is_Prime from [[Primality by Trial Division]]
with Is_Prime;
Line 216 ⟶ 368:
Ada.Text_IO.Put_Line ("is not a Mersenne number");
end;
end Mersenne;</langsyntaxhighlight>
 
{{out}}
Line 228 ⟶ 380:
<!-- {{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
Compiles, but I couldn't maxint not in library, works with manually entered maxint, bits width. Leaving some issue with newline -->
<langsyntaxhighlight lang="algol68">MODE ISPRIMEINT = INT;
PR READ "prelude/is_prime.a68" PR;
 
Line 278 ⟶ 430:
FI
 
END</langsyntaxhighlight>
Example:
<pre>
Line 284 ⟶ 436:
M +929 has a factor: +13007
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">mersenneFactors: function [q][
if not? prime? q -> print "number not prime!"
r: new q
while -> r > 0
-> shl 'r 1
d: new 1 + 2 * q
while [true][
i: new 1
p: new r
while [p <> 0][
i: new (i * i) % d
if p < 0 -> 'i * 2
if i > d -> 'i - d
shl 'p 1
]
if? i <> 1 -> 'd + 2 * q
else -> break
]
print ["2 ^" q "- 1 = 0 ( mod" d ")"]
]
 
mersenneFactors 929</syntaxhighlight>
 
{{out}}
 
<pre>2 ^ 929 - 1 = 0 ( mod 13007 )</pre>
 
=={{header|AutoHotkey}}==
ahk [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=144 discussion]
<langsyntaxhighlight lang="autohotkey">MsgBox % MFact(27) ;-1: 27 is not prime
MsgBox % MFact(2) ; 0
MsgBox % MFact(3) ; 0
Line 342 ⟶ 523:
y := i&1 ? mod(y*z,m) : y, z := mod(z*z,m), i >>= 1
Return y
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> PRINT "A factor of M929 is "; FNmersenne_factor(929)
PRINT "A factor of M937 is "; FNmersenne_factor(937)
END
Line 381 ⟶ 563:
ENDWHILE
= Y%
</syntaxhighlight>
</lang>
{{out}}
<pre>A factor of M929 is 13007
Line 387 ⟶ 569:
 
=={{header|Bracmat}}==
<langsyntaxhighlight Bracmatlang="bracmat">( ( modPow
= square P divisor highbit log 2pow
. !arg:(?P.?divisor)
Line 448 ⟶ 630:
| out$"no divisors found"
)
);</langsyntaxhighlight>
{{out}}
<pre>found some divisors of 2^!P-1 : 13007 and 348890248924938259750454781163390930305120269538278042934009621348894657205785
Line 456 ⟶ 638:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">int isPrime(int n){
if (n%2==0) return n==2;
if (n%3==0) return n==3;
Line 479 ⟶ 661:
else break;
} while(1);
printf("2^%d - 1 = 0 (mod %d)\n", q, d);}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
namespace prog
Line 527 ⟶ 709:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include <cstdint>
 
typedef uint64_t integer;
 
integer bit_count(integer n) {
integer count = 0;
for (; n > 0; count++)
n >>= 1;
return count;
}
 
integer mod_pow(integer p, integer n) {
integer square = 1;
for (integer bits = bit_count(p); bits > 0; square %= n) {
square *= square;
if (p & (1 << --bits))
square <<= 1;
}
return square;
}
 
bool is_prime(integer n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
for (integer p = 3; p * p <= n; p += 2)
if (n % p == 0)
return false;
return true;
}
 
integer find_mersenne_factor(integer p) {
for (integer k = 0, q = 1;;) {
q = 2 * ++k * p + 1;
if ((q % 8 == 1 || q % 8 == 7) && mod_pow(p, q) == 1 && is_prime(q))
return q;
}
return 0;
}
 
int main() {
std::cout << find_mersenne_factor(929) << std::endl;
return 0;
}</syntaxhighlight>
 
{{out}}
<pre>
13007
</pre>
 
=={{header|Clojure}}==
{{trans|Python}}
 
<syntaxhighlight lang="lisp">(ns mersennenumber
(:gen-class))
 
(defn m* [p q m]
" Computes (p*q) mod m "
(mod (*' p q) m))
 
(defn power
"modular exponentiation (i.e. b^e mod m"
[b e m]
(loop [b b, e e, x 1]
(if (zero? e)
x
(if (even? e) (recur (m* b b m) (quot e 2) x)
(recur (m* b b m) (quot e 2) (m* b x m))))))
 
(defn divides? [k n]
" checks if k divides n "
(= (rem n k) 0))
 
(defn is-prime? [n]
" checks if n is prime "
(cond
(< n 2) false ; 0, 1 not prime (i.e. primes are greater than one)
(= n 2) true ; 2 is prime
(= 0 (mod n 2)) false ; all other evens are not prime
:else ; check for divisors up to sqrt(n)
(empty? (filter #(divides? % n) (take-while #(<= (* % %) n) (range 2 n))))))
 
;; Max k to check
(def MAX-K 16384)
 
(defn trial-factor [p k]
" check if k satisfies 2*k*P + 1 divides 2^p - 1 "
(let [q (+ (* 2 p k) 1)
mq (mod q 8)]
(cond
(not (is-prime? q)) nil
(and (not= 1 mq)
(not= 7 mq)) nil
(= 1 (power 2 p q)) q
:else nil)))
 
(defn m-factor [p]
" searches for k-factor "
(some #(trial-factor p %) (range 16384)))
 
(defn -main [p]
(if-not (is-prime? p)
(format "M%d = 2^%d - 1 exponent is not prime" p p)
(if-let [factor (m-factor p)]
(format "M%d = 2^%d - 1 is composite with factor %d" p p factor)
(format "M%d = 2^%d - 1 is prime" p p))))
 
;; Tests different p values
(doseq [p [2,3,4,5,7,11,13,17,19,23,29,31,37,41,43,47,53,929]
:let [s (-main p)]]
(println s))
</syntaxhighlight>
{{Output}}
<pre>
M2 = 2^2 - 1 is prime
M3 = 2^3 - 1 is composite with factor 7
M4 = 2^4 - 1 exponent is not prime
M5 = 2^5 - 1 is composite with factor 31
M7 = 2^7 - 1 is composite with factor 127
M11 = 2^11 - 1 is composite with factor 23
M13 = 2^13 - 1 is composite with factor 8191
M17 = 2^17 - 1 is composite with factor 131071
M19 = 2^19 - 1 is composite with factor 524287
M23 = 2^23 - 1 is composite with factor 47
M29 = 2^29 - 1 is composite with factor 233
M31 = 2^31 - 1 is prime
M37 = 2^37 - 1 is composite with factor 223
M41 = 2^41 - 1 is composite with factor 13367
M43 = 2^43 - 1 is composite with factor 431
M47 = 2^47 - 1 is composite with factor 2351
M53 = 2^53 - 1 is composite with factor 6361
M929 = 2^929 - 1 is composite with factor 13007
</pre>
 
=={{header|CoffeeScript}}==
Line 534 ⟶ 853:
{{trans|Ruby}}
 
<langsyntaxhighlight lang="coffeescript">mersenneFactor = (p) ->
limit = Math.sqrt(Math.pow(2,p) - 1)
k = 1
Line 561 ⟶ 880:
 
checkMersenne(prime) for prime in ["2","3","4","5","7","11","13","17","19","23","29","31","37","41","43","47","53","929"]
</syntaxhighlight>
</lang>
 
<pre>M2 = 2^2-1 is prime
Line 585 ⟶ 904:
=={{header|Common Lisp}}==
{{trans|Maxima}}
<langsyntaxhighlight lang="lisp">(defun mersenne-fac (p &aux (m (1- (expt 2 p))))
(loop for k from 1
for n = (1+ (* 2 k p))
Line 591 ⟶ 910:
finally (return n)))
 
(print (mersenne-fac 929))</langsyntaxhighlight>
 
{{out}}
Line 600 ⟶ 919:
We can use a primality test from the [[Primality by Trial Division#Common_Lisp|Primality by Trial Division]] task.
 
<langsyntaxhighlight lang="lisp">(defun primep (n)
"Is N prime?"
(and (> n 1)
(or (= n 2) (oddp n))
(loop for i from 3 to (isqrt n) by 2
never (zerop (rem n i)))))</langsyntaxhighlight>
 
Specific to this task, we define modulo-power and mersenne-prime-p.
 
<langsyntaxhighlight lang="lisp">(defun modulo-power (base power modulus)
(loop with square = 1
for bit across (format nil "~b" power)
Line 627 ⟶ 946:
(primep q)
(= 1 (modulo-power 2 power q)))
(return (values nil q)))))</langsyntaxhighlight>
 
We can run the same tests from the [[#Ruby|Ruby]] entry.
Line 654 ⟶ 973:
M53 = 2**53-1 is composite with factor 6361.
M929 = 2**929-1 is composite with factor 13007.</pre>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<syntaxhighlight lang="ruby">require "big"
 
def prime?(n) # P3 Prime Generator primality test
return n | 1 == 3 if n < 5 # n: 0,1,4|false, 2,3|true
return false if n.gcd(6) != 1 # for n a P3 prime candidate (pc)
pc1, pc2 = -1, 1 # use P3's prime candidates sequence
until (pc1 += 6) > Math.sqrt(n).to_i # pcs are only 1/3 of all integers
return false if n % pc1 == 0 || n % (pc2 += 6) == 0 # if n is composite
end
true
end
 
# Compute b**e mod m
def powmod(b, e, m)
r, b = 1.to_big_i, b.to_big_i
while e > 0
r = (r * b) % m if e.odd?
b = (b * b) % m
e >>= 1
end
r
end
 
def mersenne_factor(p)
mers_num = 2.to_big_i ** p - 1
kp2 = p2 = 2.to_big_i * p
while (kp2 - 1) ** 2 < mers_num
q = kp2 + 1 # return q if it's a factor
return q if [1, 7].includes?(q % 8) && prime?(q) && (powmod(2, p, q) == 1)
kp2 += p2
end
true # could also set to `0` value to check for
end
 
def check_mersenne(p)
print "M#{p} = 2**#{p}-1 is "
f = mersenne_factor(p)
(puts "prime"; return) if f.is_a?(Bool) # or f == 0
puts "composite with factor #{f}"
end
 
(2..53).each { |p| check_mersenne(p) if prime?(p) }
check_mersenne 929</syntaxhighlight>
 
{{out}}
<pre>M2 = 2**2-1 is prime
M3 = 2**3-1 is prime
M5 = 2**5-1 is prime
M7 = 2**7-1 is prime
M11 = 2**11-1 is composite with factor 23
M13 = 2**13-1 is prime
M17 = 2**17-1 is prime
M19 = 2**19-1 is prime
M23 = 2**23-1 is composite with factor 47
M29 = 2**29-1 is composite with factor 233
M31 = 2**31-1 is prime
M37 = 2**37-1 is composite with factor 223
M41 = 2**41-1 is composite with factor 13367
M43 = 2**43-1 is composite with factor 431
M47 = 2**47-1 is composite with factor 2351
M53 = 2**53-1 is composite with factor 6361
M929 = 2**929-1 is composite with factor 13007</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.traits;
 
ulong mersenneFactor(in ulong p) pure nothrow @nogc {
Line 692 ⟶ 1,076:
void main() {
writefln("Factor of M929: %d", 929.mersenneFactor);
}</langsyntaxhighlight>
{{out}}
<pre>Factor of M929: 13007</pre>
 
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Factors_of_a_Mersenne_number#Pascal Pascal].
 
=={{header|EasyLang}}==
{{trans|C++}}
<syntaxhighlight>
fastfunc isprim num .
i = 2
while i <= sqrt num
if num mod i = 0
return 0
.
i += 1
.
return 1
.
func bit_count n .
while n > 0
n = bitshift n -1
cnt += 1
.
return cnt
.
func mod_pow p n .
square = 1
bits = bit_count p
while bits > 0
square *= square
bits -= 1
if bitand p bitshift 1 bits > 0
square = bitshift square 1
.
square = square mod n
.
return square
.
func mersenne_factor p .
while 1 = 1
k += 1
q = 2 * k * p + 1
if (q mod 8 = 1 or q mod 8 = 7) and mod_pow p q = 1 and isprim q = 1
return q
.
.
.
print mersenne_factor 929
</syntaxhighlight>
{{out}}
<pre>
13007
</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; M = 2^P - 1 , P prime
;; look for a prime divisor q such as : q < √ M, q = 1 or 7 modulo 8, q = 1 + 2kP
Line 721 ⟶ 1,157:
→ #t
 
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<syntaxhighlight lang="elixir">defmodule Mersenne do
def mersenne_factor(p) do
limit = :math.sqrt(:math.pow(2, p) - 1)
mersenne_loop(p, limit, 1)
end
defp mersenne_loop(p, limit, k) when (2*k*p - 1) > limit, do: nil
defp mersenne_loop(p, limit, k) do
q = 2*k*p + 1
if prime?(q) and rem(q,8) in [1,7] and trial_factor(2,p,q),
do: q, else: mersenne_loop(p, limit, k+1)
end
defp trial_factor(base, exp, mod) do
Integer.digits(exp, 2)
|> Enum.reduce(1, fn bit,square ->
(square * square * (if bit==1, do: base, else: 1)) |> rem(mod)
end) == 1
end
def check_mersenne(p) do
IO.write "M#{p} = 2**#{p}-1 is "
f = mersenne_factor(p)
IO.puts if f, do: "composite with factor #{f}", else: "prime"
end
def prime?(n), do: prime?(n, :math.sqrt(n), 2)
defp prime?(_, limit, i) when limit < i, do: true
defp prime?(n, limit, i) do
if rem(n,i) == 0, do: false, else: prime?(n, limit, i+1)
end
end
 
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,929]
|> Enum.each(fn p -> Mersenne.check_mersenne(p) end)</syntaxhighlight>
 
{{out}}
<pre>
M2 = 2**2-1 is prime
M3 = 2**3-1 is prime
M5 = 2**5-1 is prime
M7 = 2**7-1 is prime
M11 = 2**11-1 is composite with factor 23
M13 = 2**13-1 is prime
M17 = 2**17-1 is prime
M19 = 2**19-1 is prime
M23 = 2**23-1 is composite with factor 47
M29 = 2**29-1 is composite with factor 233
M31 = 2**31-1 is prime
M37 = 2**37-1 is composite with factor 223
M41 = 2**41-1 is composite with factor 13367
M43 = 2**43-1 is composite with factor 431
M47 = 2**47-1 is composite with factor 2351
M53 = 2**53-1 is composite with factor 6361
M929 = 2**929-1 is composite with factor 13007
</pre>
 
=={{header|Erlang}}==
Line 727 ⟶ 1,223:
The modpow function is not my original. This is a translation of python, more or less.
 
<langsyntaxhighlight lang="erlang">
-module(mersene2).
-export([prime/1,modpow/3,mf/1]).
Line 770 ⟶ 1,266:
false -> divisors(N, C-1)
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 782 ⟶ 1,278:
M929 is composite with Factor: 13007
[ok,ok,ok,ok,ok,ok,ok]
</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: combinators.short-circuit interpolate io kernel locals
math math.bits math.functions math.primes sequences ;
IN: rosetta-code.mersenne-factors
 
: mod-pow-step ( square bit m -- square' )
[ [ sq ] [ [ 2 * ] when ] bi* ] dip mod ;
 
:: mod-pow ( m q -- n )
1 :> s! m make-bits <reversed>
[ s swap q mod-pow-step s! ] each s ;
 
: halt-search? ( m q N -- ? )
dupd > [
{
[ nip 8 mod [ 1 ] [ 7 ] bi [ = ] 2bi@ or ]
[ mod-pow 1 = ] [ nip prime? ]
} 2&&
] dip or ;
 
:: find-mersenne-factor ( m -- factor/f )
1 :> k!
2 m * 1 + :> q! ! the tentative factor.
2 m ^ sqrt :> N ! upper bound on search.
[ m q N halt-search? ] [ k 1 + k! 2 k * m * 1 + q! ] until
q N > f q ? ;
 
: test-mersenne ( m -- )
dup find-mersenne-factor
[ [I M${1} is not prime: factor ${0} found.I] ]
[ [I No factor found for M${}.I] ] if* nl ;
 
929 test-mersenne</syntaxhighlight>
{{out}}
<pre>
M929 is not prime: factor 13007 found.
</pre>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: prime? ( odd -- ? )
3
begin 2dup dup * >=
Line 817 ⟶ 1,351:
 
929 factor-mersenne . \ 13007
4423 factor-mersenne . \ 0</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">PROGRAM EXAMPLE
IMPLICIT NONE
INTEGER :: exponent, factor
Line 872 ⟶ 1,406:
Mfactor = 0
END FUNCTION
END PROGRAM EXAMPLE</langsyntaxhighlight>
{{out}}
M929 has a factor: 13007
 
=={{header|FreeBASIC}}==
{{trans|C}}
<syntaxhighlight lang="freebasic">' 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
 
' test 929 plus all prime numbers below 100 which are known not to be Mersenne primes
Dim q(1 To 16) As Integer = {11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929}
For k As Integer = 1 To 16
If isPrime(q(k)) Then
Dim As Integer d, i, p, r = q(k)
While r > 0 : r Shl= 1 : Wend
d = 2 * q(k) + 1
Do
i = 1
p = r
While p <> 0
i = (i * i) Mod d
If p < 0 Then i *= 2
If i > d Then i -= d
p Shl= 1
Wend
If i <> 1 Then
d += 2 * q(k)
Else
Exit Do
End If
Loop
Print "2^"; Str(q(k)); Tab(6); " - 1 = 0 (mod"; d; ")"
Else
Print Str(q(k)); " is not prime"
End If
Next
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
2^11 - 1 = 0 (mod 23)
2^23 - 1 = 0 (mod 47)
2^29 - 1 = 0 (mod 233)
2^37 - 1 = 0 (mod 223)
2^41 - 1 = 0 (mod 13367)
2^43 - 1 = 0 (mod 431)
2^47 - 1 = 0 (mod 2351)
2^53 - 1 = 0 (mod 6361)
2^59 - 1 = 0 (mod 179951)
2^67 - 1 = 0 (mod 193707721)
2^71 - 1 = 0 (mod 228479)
2^73 - 1 = 0 (mod 439)
2^79 - 1 = 0 (mod 2687)
2^83 - 1 = 0 (mod 167)
2^97 - 1 = 0 (mod 11447)
2^929 - 1 = 0 (mod 13007)
</pre>
 
=={{header|Frink}}==
Frink has built-in routines for iterating through prime numbers and modular exponentiation. The following program will find all of the factors of the number given enough runtime.
<syntaxhighlight lang="frink">for p = primes[]
if modPow[2, 929, p] - 1 == 0
println[p]</syntaxhighlight>
{{out}}
<pre>
13007
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">MersenneSmallFactor := function(n)
local k, m, d;
if IsPrime(n) then
Line 908 ⟶ 1,520:
 
FactorsInt(2^101-1);
# [ 7432339208719, 341117531003194129 ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 991 ⟶ 1,603:
}
return int32(pow)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,003 ⟶ 1,615:
Using David Amos module Primes [https://web.archive.org/web/20121130222921/http://www.polyomino.f2s.com/david/haskell/codeindex.html] for prime number testing:
 
<langsyntaxhighlight lang="haskell">import Data.List
import HFM.Primes (isPrime)
import Control.Monad
Line 1,015 ⟶ 1,627:
map (succ.(2*m*)). enumFromTo 1 $ m `div` 2
bs = int2bin m
pm n b = 2^b*n*n</langsyntaxhighlight>
 
<langsyntaxhighlight lang="haskell">*Main> trialfac 929
[13007]</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,024 ⟶ 1,636:
 
The following works in both languages:
<langsyntaxhighlight lang="unicon">procedure main(A)
p := integer(A[1]) | 929
write("M",p," has a factor ",mfactor(p))
Line 1,055 ⟶ 1,667:
}
return
end</langsyntaxhighlight>
 
Sample runs:
Line 1,068 ⟶ 1,680:
=={{header|J}}==
 
<langsyntaxhighlight lang="j">trialfac=: 3 : 0
qs=. (#~8&(1=|+.7=|))(#~1&p:)1+(*(1x+i.@<:@<.)&.-:)y
qs#~1=qs&|@(2&^@[**:@])/ 1,~ |.#: y
)</langsyntaxhighlight>
 
{{out|Examples}}
<langsyntaxhighlight lang="j">trialfac 929
13007</langsyntaxhighlight>
<syntaxhighlight lang ="j">trialfac 44497</langsyntaxhighlight>
Empty output --> No factors found.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
import java.math.BigInteger;
 
Line 1,149 ⟶ 1,761:
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,176 ⟶ 1,788:
=={{header|JavaScript}}==
 
<langsyntaxhighlight lang="javascript">function mersenne_factor(p){
var limit, k, q
limit = Math.sqrt(Math.pow(2,p) - 1)
Line 1,216 ⟶ 1,828:
f = mersenne_factor(p)
console.log(f == null ? "prime" : "composite with factor "+f)
}</langsyntaxhighlight>
 
<pre>
Line 1,227 ⟶ 1,839:
</pre>
 
=={{header|Mathematicajq}}==
'''Adapted from [[#Wren|Wren]]'''
 
'''Works with jq, the C implementation of jq'''
 
'''Works with gojq, the Go implementation of jq'''
 
'''Works with jaq, the Rust implementation of jq'''
 
The following has been written with the task requirements (notably M929) in
mind, and for compatibility with the three implementations of jq
indicated above. For speed and robustness with respect to very large
values of P, variants should be considered.
<syntaxhighlight lang=jq>
# Generic filters:
 
# Integer division (for gojq and jaq)
# If $j is 0, then an error condition is raised;
# otherwise, assuming infinite-precision integer arithmetic,
# if the input and $j are integers, then the result will be an integer.
def idivide($j):
(. % $j) as $mod
| (. - $mod) / $j | round;
 
# Convert the input integer to a stream of 0s and 1s, least significant bit first
def bitwise:
recurse( if . >= 2 then idivide(2) else empty end) | . % 2;
 
def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
elif ($n % 5 == 0) then $n == 5
elif ($n % 7 == 0) then $n == 7
elif ($n % 11 == 0) then $n == 11
elif ($n % 13 == 0) then $n == 13
elif ($n % 17 == 0) then $n == 17
elif ($n % 19 == 0) then $n == 19
else sqrt as $s
| 23
| until( . > $s or ($n % . == 0); . + 2)
| . > $s
end;
 
### Factors of Mersene numbers
 
def trialFactor($base; $exp; $mod):
[$exp | bitwise] as $bits
| ($bits|length) as $length
| reduce range( 0; $length) as $i (1;
(. * . * (if $bits[$length-$i-1] == 1 then $base else 1 end)) % $mod )
| . == 1 ;
 
def mersenneFactor($p):
((pow(2;$p) - 1) | sqrt | floor) as $limit
| {k: 1}
| until ((2*.k*$p - 1) >= $limit or .emit;
(2*.k*$p + 1 ) as $q
| if ($q%8 == 1 or $q%8 == 7) and trialFactor(2; $p; $q) and ($q | is_prime)
then .emit = $q # q is a factor of 2^p - 1
else .k += 1
end)
| if .emit then .emit else null end;
 
### Examples:
 
def m: [3, 5, 11, 17, 23, 29, 31, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929];
 
m[]
| mersenneFactor(.) as $f
| "2^\(.) - 1 is " +
if $f then "composite (factor \($f))"
else "prime"
end
</syntaxhighlight>
{{output}}
<pre>
2^3 - 1 is prime
2^5 - 1 is prime
2^11 - 1 is composite (factor 23)
2^17 - 1 is prime
2^23 - 1 is composite (factor 47)
2^29 - 1 is composite (factor 233)
2^31 - 1 is prime
2^37 - 1 is composite (factor 223)
2^41 - 1 is composite (factor 13367)
2^43 - 1 is composite (factor 431)
2^47 - 1 is composite (factor 2351)
2^53 - 1 is composite (factor 6361)
2^59 - 1 is composite (factor 179951)
2^67 - 1 is composite (factor 193707721)
2^71 - 1 is composite (factor 228479)
2^73 - 1 is composite (factor 439)
2^79 - 1 is composite (factor 2687)
2^83 - 1 is composite (factor 167)
2^97 - 1 is composite (factor 11447)
2^929 - 1 is composite (factor 13007)
</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia"># v0.6
 
using Primes
 
function mersennefactor(p::Int)::Int
q = 2p + 1
while true
if log2(q) > p / 2
return -1
elseif q % 8 in (1, 7) && Primes.isprime(q) && powermod(2, p, q) == 1
return q
end
q += 2p
end
end
 
for i in filter(Primes.isprime, push!(collect(1:20), 929))
mf = mersennefactor(i)
if mf != -1 println("M$i = ", mf, " × ", (big(2) ^ i - 1) ÷ mf)
else println("M$i is prime") end
end</syntaxhighlight>
 
{{out}}
<pre>M2 is prime
M3 is prime
M5 is prime
M7 is prime
M11 = 23 × 89
M13 is prime
M17 is prime
M19 is prime
M929 = 13007 × 34889024892493825975045478116339093030512026953827804293400962134
88946572057852012474541189660261508521493994102599382170621001921687473524507195
61908445272675574320888385228421992652298715687625495638077382028762529439880103
124705348782610789919949159935587158612289264184273</pre>
 
=={{header|Kotlin}}==
{{trans|C}}
<syntaxhighlight lang="scala">// version 1.0.6
 
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
 
fun main(args: Array<String>) {
// test 929 plus all prime numbers below 100 which are known not to be Mersenne primes
val q = intArrayOf(11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929)
for (k in 0 until q.size) {
if (isPrime(q[k])) {
var i: Long
var d: Int
var p: Int
var r: Int = q[k]
while (r > 0) r = r shl 1
d = 2 * q[k] + 1
while (true) {
i = 1L
p = r
while (p != 0) {
i = (i * i) % d
if (p < 0) i *= 2
if (i > d) i -= d
p = p shl 1
}
if (i != 1L)
d += 2 * q[k]
else
break
}
println("2^${"%3d".format(q[k])} - 1 = 0 (mod $d)")
} else {
println("${q[k]} is not prime")
}
}
}</syntaxhighlight>
 
{{out}}
<pre>
2^ 11 - 1 = 0 (mod 23)
2^ 23 - 1 = 0 (mod 47)
2^ 29 - 1 = 0 (mod 233)
2^ 37 - 1 = 0 (mod 223)
2^ 41 - 1 = 0 (mod 13367)
2^ 43 - 1 = 0 (mod 431)
2^ 47 - 1 = 0 (mod 2351)
2^ 53 - 1 = 0 (mod 6361)
2^ 59 - 1 = 0 (mod 179951)
2^ 67 - 1 = 0 (mod 193707721)
2^ 71 - 1 = 0 (mod 228479)
2^ 73 - 1 = 0 (mod 439)
2^ 79 - 1 = 0 (mod 2687)
2^ 83 - 1 = 0 (mod 167)
2^ 97 - 1 = 0 (mod 11447)
2^929 - 1 = 0 (mod 13007)
</pre>
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">on modPow (b, e, m)
bits = getBits(e)
sq = 1
repeat while TRUE
tb = bits[1]
bits.deleteAt(1)
sq = sq*sq
if tb then sq=sq*b
sq = sq mod m
if bits.count=0 then return sq
end repeat
end
 
on getBits (n)
bits = []
f = 1
repeat while TRUE
bits.addAt(1, bitAnd(f, n)>0)
f = f * 2
if f>n then exit repeat
end repeat
return bits
end</syntaxhighlight>
 
<syntaxhighlight lang="lingo">repeat with i = 2 to the maxInteger
if modPow(2, 929, i)=1 then
put "M929 has a factor: " & i
exit repeat
end if
end repeat</syntaxhighlight>
 
{{out}}
<pre>
-- "M929 has a factor: 13007"
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Believe it or not, this type of test runs faster in Mathematica than the squaring version described above.
 
<syntaxhighlight lang="mathematica">For[i = 2, i < Prime[1000000], i = NextPrime[i],
<lang mathematica>
For[i = 2, i < Prime[1000000], i = NextPrime[i],
If[Mod[2^44497, i] == 1,
Print["divisible by "<>i]]]; Print["prime test passed; call Lucas and Lehmer"]</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">mersenne_fac(p) := block([m: 2^p - 1, k: 1],
while mod(m, 2 * k * p + 1) # 0 do k: k + 1,
2 * k * p + 1
Line 1,242 ⟶ 2,097:
 
mersenne_fac(929);
/* 13007 */</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">import math
 
proc isPrime(a: int): bool =
Line 1,271 ⟶ 2,126:
if i != 1: d += 2 * q
else: break
echo "2^",q," - 1 = 0 (mod ",d,")"</langsyntaxhighlight>
{{out}}
<pre>2^929 - 1 = 0 (mod 13007)</pre>
Line 1,280 ⟶ 2,135:
(GNU Octave has a <code>isprime</code> built-in test)
 
<langsyntaxhighlight lang="octave">% test a bit; lsb is 1 (like built-in bit* ops)
function b = bittst(n, p)
b = bitand(n, 2^(p-1)) > 0;
Line 1,313 ⟶ 2,168:
endfunction
 
printf("%d\n", Mfactor(929));</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
This version takes about 15 microseconds to find a factor of 2<sup>929</sup> &minus; 1.
<langsyntaxhighlight lang="parigp">factorMersenne(p)={
forstep(q=2*p+1,sqrt(2)<<(p\2),2*p,
[1,0,0,0,0,0,1][q%8] && Mod(2, q)^p==1 && return(q)
Line 1,323 ⟶ 2,178:
1<<p-1
};
factorMersenne(929)</langsyntaxhighlight>
 
This implementation seems to be broken:
<langsyntaxhighlight lang="parigp">TM(p) = local(status=1, i=1, len=0, S=0);{
printp("Test TM \t...");
S=2*p+1;
Line 1,345 ⟶ 2,200:
);
return(status);
}</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{trans|Fortran}}
<langsyntaxhighlight lang="pascal">program FactorsMersenneNumber(input, output);
 
function isPrime(n: longint): boolean;
Line 1,432 ⟶ 2,287:
else
writeln('M', exponent, ' (2**', exponent, ' - 1) has the factor: ', factor);
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,441 ⟶ 2,296:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use utf8;
 
Line 1,501 ⟶ 2,356:
print $f? "M$m = $x = $q × @{[$x / $q]}\n"
: "M$m = $x is prime\n";
}</langsyntaxhighlight>
{{out}}
<pre>M2 = 3 is prime
Line 1,516 ⟶ 2,371:
 
Following the task introduction, this uses GMP's modular exponentiation and simple probable prime test for the small numbers, then looks for small factors before doing a Lucas-Lehmer test. For ranges above about p=2000, looking for small factors this way saves time (the amount of testing should be adjusted based on the input size and platform -- this example just uses a fixed amount). Note as well that the Lucas-Lehmer test shown here is ignoring the large speedup we can get by optimizing the modulo operation, but that's a different task.
<langsyntaxhighlight lang="perl">use Math::GMP;
 
# Use GMP's simple probable prime test.
Line 1,545 ⟶ 2,400:
print "M$p is ", is_mersenne_prime($p) ? "prime" : "composite", "\n";
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,576 ⟶ 2,431:
</pre>
 
=={{header|Perl 6Phix}}==
Translation/Amalgamation of BBC BASIC, D, and Go
{{Works with|rakudo|2015.12}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang perl6>my @primes = 2, 3, -> $n is copy {
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
repeat { $n += 2 } until $n %% none do for @primes -> $p {
<span style="color: #008080;">function</span> <span style="color: #000000;">modpow</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
last if $p > sqrt($n);
<span style="color: #004080;">atom</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span>
$p;
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span>
}
<span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x</span>
$n;
<span style="color: #008080;">while</span> <span style="color: #000000;">i</span> <span style="color: #008080;">do</span>
} ... *;
<span style="color: #008080;">if</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">*</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
multi factors(1) { 1 }
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
multi factors(Int $remainder is copy) {
<span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">*</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
gather for @primes -> $factor {
<span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
if $factor * $factor > $remainder {
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
take $remainder if $remainder > 1;
<span style="color: #008080;">return</span> <span style="color: #000000;">y</span>
last;
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
}
while $remainder %% $factor {
<span style="color: #008080;">function</span> <span style="color: #000000;">mersenne_factor</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
take $factor;
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
last if ($remainder div= $factor) === 1;
<span style="color: #004080;">atom</span> <span style="color: #000000;">limit</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">))-</span><span style="color: #000000;">1</span>
}
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
}
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
}
<span style="color: #004080;">atom</span> <span style="color: #000000;">q</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">p</span><span style="color: #0000FF;">*</span><span style="color: #000000;">k</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">1</span>
 
<span style="color: #008080;">if</span> <span style="color: #000000;">q</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">limit</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
sub is_prime($x) { (state %){$x} //= factors($x) == 1 }
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">q</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">),{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">})</span>
 
<span style="color: #008080;">and</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">q</span><span style="color: #0000FF;">)</span>
sub mtest($bits, $p) {
<span style="color: #008080;">and</span> <span style="color: #000000;">modpow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #000000;">q</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
my @bits = $bits.base(2).comb;
<span style="color: #008080;">return</span> <span style="color: #000000;">q</span>
loop (my $sq = 1; @bits; $sq %= $p) {
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
$sq *= $sq;
<span style="color: #000000;">k</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
$sq += $sq if 1 == @bits.shift;
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
}
<span style="color: #008080;">return</span> <span style="color: #000000;">0</span>
$sq == 1;
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
}
 
<span style="color: #004080;">sequence</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">11</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">23</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">29</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">37</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">41</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">43</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">47</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">53</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">59</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">67</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">71</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">73</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">79</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">83</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">97</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">929</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">937</span><span style="color: #0000FF;">}</span>
for flat 2 .. 60, 929 -> $m {
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
next unless is_prime($m);
<span style="color: #004080;">integer</span> <span style="color: #000000;">ti</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
my $f = 0;
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"A factor of M%d is %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mersenne_factor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">)})</span>
my $x = 2**$m - 1;
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
my $q;
<!--</syntaxhighlight>-->
for 1..* -> $k {
{{Out}}
$q = 2 * $k * $m + 1;
<pre>
next unless $q % 8 == 1|7 or is_prime($q);
A factor of M11 is 23
last if $q * $q > $x or $f = mtest($m, $q);
A factor of M23 is 47
}
A factor of M29 is 233
 
A factor of M37 is 223
say $f ?? "M$m = $x\n\t= $q × { $x div $q }"
A factor of M41 is 13367
!! "M$m = $x is prime";
A factor of M43 is 431
}</lang>
A factor of M47 is 2351
{{out}}
A factor of M53 is 6361
<pre>M2 = 3 is prime
M3A =factor 7of M59 is prime179951
M5A =factor 31of M67 is prime193707721
M7A =factor 127of M71 is prime228479
A factor of M73 is 439
M11 = 2047
A factor of M79 is 2687
= 23 × 89
M13A =factor 8191of M83 is prime167
M17A =factor 131071of M97 is prime11447
M19A =factor 524287of M929 is prime13007
A factor of M937 is 28111
M23 = 8388607
</pre>
= 47 × 178481
M29 = 536870911
= 233 × 2304167
M31 = 2147483647 is prime
M37 = 137438953471
= 223 × 616318177
M41 = 2199023255551
= 13367 × 164511353
M43 = 8796093022207
= 431 × 20408568497
M47 = 140737488355327
= 2351 × 59862819377
M53 = 9007199254740991
= 6361 × 1416003655831
M59 = 576460752303423487
= 179951 × 3203431780337
M929 = 4538015467766671944574165338592225830478699345884382504442663144885072806275648112625635725391102144133907238129251016389326737199538896813326509341743147661691195191795226666084858428449394948944821764472508048114220424520501343042471615418544488778723282182172070046459244838911
= 13007 × 348890248924938259750454781163390930305120269538278042934009621348894657205785201247454118966026150852149399410259938217062100192168747352450719561908445272675574320888385228421992652298715687625495638077382028762529439880103124705348782610789919949159935587158612289264184273</pre>
 
=={{header|PHP}}==
{{trans|D}}
Requires bcmath
<langsyntaxhighlight lang="php">echo 'M929 has a factor: ', mersenneFactor(929), '</br>';
 
function mersenneFactor($p) {
Line 1,679 ⟶ 2,517:
}
return true;
}</langsyntaxhighlight>
 
{{out}}
Line 1,685 ⟶ 2,523:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de **Mod (X Y N)
(let M 1
(loop
Line 1,715 ⟶ 2,553:
(prime? Q)
(= 1 (**Mod 2 P Q)) )
Q ) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (for P (2 3 4 5 7 11 13 17 19 23 29 31 37 41 43 47 53 929)
Line 1,742 ⟶ 2,580:
M53 = 2**53-1 is composite with factor 6361
M929 = 2**929-1 is composite with factor 13007</pre>
 
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">
mersenne_factor(P, F) :-
prime(P),
once((
between(1, 100_000, K), % Fail if we can't find a small factor
Q is 2*K*P + 1,
test_factor(Q, P, F))).
 
test_factor(Q, P, prime) :- Q*Q > (1 << P - 1), !.
test_factor(Q, P, Q) :-
R is Q /\ 7, member(R, [1, 7]),
prime(Q),
powm(2, P, Q) =:= 1.
 
 
wheel235(L) :-
W = [4, 2, 4, 2, 4, 6, 2, 6 | W],
L = [1, 2, 2 | W].
 
prime(N) :-
N >= 2,
wheel235(W),
prime(N, 2, W).
 
prime(N, D, _) :- D*D > N, !.
prime(N, D, [A|As]) :-
N mod D =\= 0,
D2 is D + A, prime(N, D2, As).
</syntaxhighlight>
{{Out}}
<pre>
?- mersenne_factor(23, X).
X = 47.
 
?- mersenne_factor(5,X).
X = prime.
 
?- mersenne_factor(25,X).
false.
 
?- mersenne_factor(929,X).
X = 13007.
 
?- mersenne_factor(127,X).
false.
</pre>
 
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">def is_prime(number):
return True # code omitted - see Primality by Trial Division
 
Line 1,769 ⟶ 2,655:
print "No factor found for M%d" % exponent
else:
print "M%d has a factor: %d" % (exponent, factor)</langsyntaxhighlight>
 
{{out|Example}}
Line 1,778 ⟶ 2,664:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
Line 1,799 ⟶ 2,685:
 
(mersenne-factor 929)
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="racket">
13007
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" line>sub mtest($bits, $p) {
my @bits = $bits.base(2).comb;
loop (my $sq = 1; @bits; $sq %= $p) {
$sq ×= $sq;
$sq += $sq if 1 == @bits.shift;
}
$sq == 1;
}
 
for flat 2 .. 60, 929 -> $m {
next unless is-prime($m);
my $f = 0;
my $x = 2**$m - 1;
my $q;
for 1..* -> $k {
$q = 2 × $k × $m + 1;
next unless $q % 8 == 1|7 or is-prime($q);
last if $q × $q > $x or $f = mtest($m, $q);
}
 
say $f ?? "M$m = $x\n\t= $q × { $x div $q }"
!! "M$m = $x is prime";
}</syntaxhighlight>
{{out}}
<pre>M2 = 3 is prime
M3 = 7 is prime
M5 = 31 is prime
M7 = 127 is prime
M11 = 2047
= 23 × 89
M13 = 8191 is prime
M17 = 131071 is prime
M19 = 524287 is prime
M23 = 8388607
= 47 × 178481
M29 = 536870911
= 233 × 2304167
M31 = 2147483647 is prime
M37 = 137438953471
= 223 × 616318177
M41 = 2199023255551
= 13367 × 164511353
M43 = 8796093022207
= 431 × 20408568497
M47 = 140737488355327
= 2351 × 59862819377
M53 = 9007199254740991
= 6361 × 1416003655831
M59 = 576460752303423487
= 179951 × 3203431780337
M929 = 4538015467766671944574165338592225830478699345884382504442663144885072806275648112625635725391102144133907238129251016389326737199538896813326509341743147661691195191795226666084858428449394948944821764472508048114220424520501343042471615418544488778723282182172070046459244838911
= 13007 × 348890248924938259750454781163390930305120269538278042934009621348894657205785201247454118966026150852149399410259938217062100192168747352450719561908445272675574320888385228421992652298715687625495638077382028762529439880103124705348782610789919949159935587158612289264184273</pre>
 
=={{header|REXX}}==
REXX practically has no limit (well, up to around 8 million) on the number of decimal digits (precision).
<lang rexx>/*REXX program uses exponent─&─mod operator to test possible Mersenne numbers.*/
numeric digits 500 /*dealing with some ginormous numbers. */
 
This REXX version automatically adjusts the &nbsp; '''numeric digits''' &nbsp; to whatever is needed.
do j=1 to 61; z=j /*when J reaches 61, it turns into 929.*/
<syntaxhighlight lang="rexx">/*REXX program uses exponent─and─mod operator to test possible Mersenne numbers. */
if z==61 then z=929 /*now, a switcheroo, 61 turns into 929.*/
numeric digits 20 /*this will be increased if necessary. */
if \isPrime(z) then iterate /*if Z isn't a prime, keep plugging.*/
parse arg N spec r=testM(z) /*If Z is prime, give Z the 3rd/*obtain optional arguments from the degree.CL*/
if N=='' | N=="," then N= 88 /*Not specified? Then use the default.*/
if r==0 then say right('M'z,8) "──────── is a Mersenne prime."
if spec=='' | spec=="," then spec= 920 970 /* " " else say right('M'z,48) "is composite, a factor:" r" " */
do j=1; z= j /*process a range, & then do some more.*/
if j==N then j= word(spec, 1) /*now, use the high range of numbers. */
if j>word(spec, 2) then leave /*done with " " " " " */
if \isPrime(z) then iterate /*if Z isn't a prime, keep plugging.*/
r= commas( testMer(z) ); L= length(r) /*add commas; get its new length. */
if r==0 then say right('M'z, 10) "──────── is a Mersenne prime."
else say right('M'z, 50) "is composite, a factor:"right(r, max(L, 13) )
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*────────────────────────────────────────────────────────────────────────────*/
isPrimecommas: procedure; parse arg x_; if wordpos(x,'2do jc=length(_)-3 5 7')\to 1 by -3; _==0insert(',', _, jc); end; then return 1_
/*──────────────────────────────────────────────────────────────────────────────────────*/
if x<11 then return 0; if x//2==0 | x//3 ==0 then return 0
isPrime: procedure; parse arg x; do j=5 byif 6;wordpos(x, '2 3 5 7') if x//j\== 0 | x//(j+2)==0 then return 01
if x<11 then return 0; if j*j>x//2 == 0 | x//3 == 0 then return 10
enddo j=5 by 6; if x//*j* == 0 | x//(j+2) == 0 then return 0
if j*j>x then return 1 /*◄─┐ ___ */
/*────────────────────────────────────────────────────────────────────────────*/
end /*j*/ /* └─◄ Is j>√ x ? Then return 1*/
iSqrt: procedure; parse arg x; r=0; q=1; do while q<=x; q=q*4; end
/*──────────────────────────────────────────────────────────────────────────────────────*/
do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end;end
iSqrt: procedure; parse arg x; #= 1; r= 0; do while #<=x; #= # * 4
return r
end /*while*/
/*────────────────────────────────────────────────────────────────────────────*/
modPow: procedure; parse arg base,n,div; sq= do while #>1; #= # % 4; $ _=x2b(d2x(n))+0 x-r-#; r= r % 2
if _>=0 then do; x= _; do until $r==''; r + sq=sq**2#
if left($,1) then sq=sq*base//div; $=substr($,2)end
end /*while*/ end /*untiliSqrt ≡ integer ···square root.*/
return r /*───── ─ ── ─ ─ */
return sq
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*────────────────────────────────────────────────────────────────────────────*/
testMtestMer: procedure; parse arg x; p= 2**x /*test a[↓] do we possiblehave Mersenneenough primedigits?*/
$$=x2b( d2x(x) ) + 0
sqRoot=iSqrt(2**x) /*iSqrt is: integer square root*/
if pos('E',p)\==0 then do; parse var p "E" _; numeric digits _ + 2; p= /2*───── ─ ── ─ ─ */x
do k=1; q=2*k*x + 1 /* _____ */end
!.= 1; !.1= 0; !.7= 0 if q>sqRoot then return 0 /*Isarray used q>√(2^x)?for a Aquicker Mersennetest. prime*/
_R=q //iSqrt(p) 8 /*obtain theinteger remaindersquare whenroot ÷of 8.P*/
if _\==1 & _\ do k==72 by 2; then iterate / q= k*mustx be either+ one1 /*(shortcut) compute value orof Q. seven*/
if \isPrime( m= q) // 8 then iterate /*Qobtain the ¬prime?remainder Thenwhen keep÷ on8. looking*/
if modPow(2,x,q)==1!.m then returniterate q /*NotM amust prime?be either Returnone aor factorseven.*/
parse var q '' -1 _; if _==5 then iterate /*last digit a five ? */
end /*k*/</lang>
if q// 3==0 then iterate /*divisible by three? */
if q// 7==0 then iterate /* " " seven? */
if q//11==0 then iterate /* " " eleven?*/
/* ____ */
if q>R then return 0 /*Is q>√2**x ? A Mersenne prime*/
sq= 1; $= $$ /*obtain binary version from $. */
do until $==''; sq= sq*sq
parse var $ _ 2 $ /*obtain 1st digit and the rest. */
if _ then sq= (sq+sq) // q
end /*until*/
if sq==1 then return q /*Not a prime? Return a factor.*/
end /*k*/</syntaxhighlight>
Program note: &nbsp; the &nbsp; '''iSqrt''' &nbsp; function computes the integer square root of a non-negative integer without using any floating point, just integers.
 
'''{{out|output''' |text=&nbsp; when using the default input:(two) ranges of numbers:}}
<pre>
M2 ──────── is a Mersenne prime.
M3 ──────── is a Mersenne prime.
M5 ──────── is a Mersenne prime.
M7 ──────── is a Mersenne prime.
M11 is composite, a factor: 23
M13 ──────── is a Mersenne prime.
M17 ──────── is a Mersenne prime.
M19 ──────── is a Mersenne prime.
M23 is composite, a factor: 47
M29 is composite, a factor: 233
M31 ──────── is a Mersenne prime.
M37 is composite, a factor: 223
M41 is composite, a factor: 13,367
M43 is composite, a factor: 431
M47 is composite, a factor: 2,351
M53 is composite, a factor: 6,361
M59 is composite, a factor: 179,951
M61 ──────── is a Mersenne prime.
M67 is composite, a factor: 193,707,721
M71 is composite, a factor: 228,479
M73 is composite, a factor: 439
M79 is composite, a factor: 2,687
M83 is composite, a factor: 167
M929 is composite, a factor: 13,007
M937 is composite, a factor: 28,111
M941 is composite, a factor: 7,529
M947 is composite, a factor: 295,130,657
M953 is composite, a factor: 343,081
M967 is composite, a factor: 23,209
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Factors of a Mersenne number
 
see "A factor of M929 is " + mersennefactor(929) + nl
see "A factor of M937 is " + mersennefactor(937) + nl
 
func mersennefactor(p)
if not isprime(p)
return -1
ok
for k = 1 to 50
q = 2*k*p + 1
if (q && 7) = 1 or (q && 7) = 7
if isprime(q)
if modpow(2, p, q) = 1
return q
ok
ok
ok
next
return 0
func isprime(num)
if (num <= 1) return 0 ok
if (num % 2 = 0) and num != 2 return 0 ok
for i = 3 to floor(num / 2) -1 step 2
if (num % i = 0) return 0 ok
next
return 1
 
func modpow(x,n,m)
i = n
y = 1
z = x
while i > 0
if i & 1
y = (y * z) % m
ok
z = (z * z) % m
i = (i >> 1)
end
return y
</syntaxhighlight>
Output:
<pre>
A factor of M929 is 13007
A factor of M937 is 28111
</pre>
 
=={{header|RPL}}==
{{works with|HP|48}}
<code>PRIM?</code> is defined at [[Primality by trial division#RPL|Primality by trial division]]
{| class="wikitable" ≪
! RPL code
! Comment
|-
|
≪ SWAP R→B → quotient power
≪ 2 power B→R LN 2 LN / FLOOR ^ R→B
1
'''WHILE''' OVER B→R '''REPEAT'''
SQ
'''IF''' OVER power AND B→R '''THEN''' DUP + '''END'''
quotient MOD
SWAP SR SWAP
'''END''' SWAP DROP
≫ ≫ '<span style="color:blue">MODPOW</span>' STO
≪ 2 OVER ^ 1 - √ 0 → power max k
≪ 1
'''WHILE''' 'k' INCR 2 * 1 + DUP max ≤ '''REPEAT'''
'''IF''' { 1 7 } OVER 8 MOD POS THEN
'''IF''' DUP <span style="color:blue">PRIM?</span> THEN
'''IF''' power OVER <span style="color:blue">MODPOW</span> 1 == '''THEN'''
SWAP max 'k' STO '''END'''
'''END END'''
DROP
'''END''' DROP
≫ '<span style="color:blue">MFACT</span>' STO
|
<span style="color:blue">MODPOW</span> ''( power quotient → remainder )''
create top-bit mask
square = 1
while mask is not zero
square *= square
if unmasked bit = 1 then square += square
square = square mod quotient
shift mask right
clean stack
return square
<span style="color:blue">MFACT</span> ''( N → factor ) ''
factor = 1
while 2k+1 ≤ sqrt(M(N))
if 2k+1 mod 8 is equal to 1 or 7
if 2k+1 prime
is 2K+1 a factor of M(N) ?
if yes, exit loop
return factor
|}
929 <span style="color:blue">MFACT</span>
{{out}}
<pre>
1: 13007
M2 ──────── is a Mersenne prime.
M3 ──────── is a Mersenne prime.
M5 ──────── is a Mersenne prime.
M7 ──────── is a Mersenne prime.
M11 is composite, a factor: 23
M13 ──────── is a Mersenne prime.
M17 ──────── is a Mersenne prime.
M19 ──────── is a Mersenne prime.
M23 is composite, a factor: 47
M29 is composite, a factor: 233
M31 ──────── is a Mersenne prime.
M37 is composite, a factor: 223
M41 is composite, a factor: 13367
M43 is composite, a factor: 431
M47 is composite, a factor: 2351
M53 is composite, a factor: 6361
M59 is composite, a factor: 179951
M929 is composite, a factor: 13007
</pre>
Factor found in 69 minutes on a 4-bit HP-48SX calculator.
 
=={{header|Ruby}}==
{{works with|Ruby|1.9.3+}}
<langsyntaxhighlight lang="ruby">require 'prime'
 
def mersenne_factor(p)
Line 1,905 ⟶ 2,985:
 
Prime.each(53) { |p| check_mersenne p }
check_mersenne 929</langsyntaxhighlight>
 
{{out}}
Line 1,925 ⟶ 3,005:
M53 = 2**53-1 is composite with factor 6361
M929 = 2**929-1 is composite with factor 13007</pre>
 
=={{header|Rust}}==
{{trans|C++}}
<syntaxhighlight lang="rust">fn bit_count(mut n: usize) -> usize {
let mut count = 0;
while n > 0 {
n >>= 1;
count += 1;
}
count
}
 
fn mod_pow(p: usize, n: usize) -> usize {
let mut square = 1;
let mut bits = bit_count(p);
while bits > 0 {
square = square * square;
bits -= 1;
if (p & (1 << bits)) != 0 {
square <<= 1;
}
square %= n;
}
return square;
}
 
fn is_prime(n: usize) -> bool {
if n < 2 {
return false;
}
if n % 2 == 0 {
return n == 2;
}
if n % 3 == 0 {
return n == 3;
}
let mut p = 5;
while p * p <= n {
if n % p == 0 {
return false;
}
p += 2;
if n % p == 0 {
return false;
}
p += 4;
}
true
}
 
fn find_mersenne_factor(p: usize) -> usize {
let mut k = 0;
loop {
k += 1;
let q = 2 * k * p + 1;
if q % 8 == 1 || q % 8 == 7 {
if mod_pow(p, q) == 1 && is_prime(p) {
return q;
}
}
}
}
 
fn main() {
println!("{}", find_mersenne_factor(929));
}</syntaxhighlight>
 
{{out}}
<pre>
13007
</pre>
 
=={{header|Scala}}==
Line 1,930 ⟶ 3,081:
 
===Full-blown version===
<syntaxhighlight lang="scala">
<lang Scala>/** Find factors of a Mersenne number
/** Find factors of a Mersenne number
*
* The implementation finds factors for M929 and further.
*
* @example M59 = 2^059 - 1 = 576460752303423487 ( 2 msec)
* @example = 179951 × 3203431780337.
*/
object FactorMersenneFactorsOfAMersenneNumber extends App {
 
val two: BigInt = 2
 
def sieve(nums: Stream[Int]): Stream[Int] =
Stream.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0)))
// An infinite stream of primes, lazy evaluation and memo-ized
val oddPrimes = sieve(StreamLazyList.from(3, 2))
 
def primes = sieve(2 #:: oddPrimes)
def sieve(nums: LazyList[Int]): LazyList[Int] =
LazyList.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0)))
 
def mersenne(pprimes: LazyList[Int)] = sieve(two2 pow#:: poddPrimes) - 1
 
def factorMersenne(p: Int): Option[Long] = {
Line 1,957 ⟶ 3,108:
 
// Build a stream of factors from (2*p+1) step-by (2*p)
def s(a: Long): StreamLazyList[Long] = a #:: s(a + (2 * p)) // Build stream of possible factors
 
// Limit and Filter Stream and then take the head element
Line 1,963 ⟶ 3,114:
e.headOption
}
 
def mersenne(p: Int): BigInt = (two pow p) - 1
 
// Test
(primes takeWhile (_ <= 97)) ++ List(929, 937) foreach { p => { // Needs some intermediate results for nice formatting
val nMersenne = mersenne(p);
{ // Needs some intermediate results for nice formatting
val nMersenne = mersenne(p); val lit = fs"${nMersenne}%30d"
val preAmble = f"${s"M${p}"}%4s = 2^$p%03d - 1 = ${lit}%s"
 
val datum = System.nanoTime
val result = factorMersenne(p)
val mSec = ((System.nanoTime - datum) / 1.e0e+6).round
 
def decStr = { if (lit.length > 30) f"(M has ${lit.length}%3d dec)" else "" }
def sPrime = { if (resultlit.isEmptylength > 30) f"(M ishas a${lit.length}%3d Mersenne prime number.dec)" else " " * 28 }
}
 
def sPrime: String = {
println(f"$preAmble${sPrime} ${f"($mSec%,1d"}%13s msec)")
if (!result.isEmpty) " is a Mersenne prime number." else " " * 28
println(f"${decStr}%-17s = ${result.get} × ${nMersenne / result.get}")
}
 
println(f"$preAmble${sPrime} ${f"($mSec%,1d"}%13s msec)")
if (result.isDefined)
println(f"${decStr}%-17s = ${result.get} × ${nMersenne / result.get}")
}
}
}</lang>
}
</syntaxhighlight>
{{out}}
<pre style="height:40ex;overflow:scroll"> M2 = 2^002 - 1 = 3 is a Mersenne prime number. (63 msec)
Line 2,034 ⟶ 3,193:
This works with PLT Scheme, other implementations only need to change the inclusion.
 
<langsyntaxhighlight lang="scheme">
#lang scheme
 
Line 2,056 ⟶ 3,215:
(= 1 (modpow p i))))
i))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,068 ⟶ 3,227:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func boolean: isPrime (in integer: number) is func
Line 2,131 ⟶ 3,290:
begin
writeln("Factor of M929: " <& mersenneFactor(929));
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#isPrime isPrime],
Line 2,142 ⟶ 3,301:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func mtest(b, p) {
var bits = b.base(2).to_i.digits
for (var sq = 1; bits; sq %= p) {
sq *= sq;
sq += sq if bits.shift.is_one==1
}
sq == 1
}
 
for m in (2..60 -> grep{ .is_prime} +}, [929]) {
var f = 0
var x = (2**m - 1)
var q
Inf.times { |k|
q = (2*k*m + 1)
q%8 ~~ [1,7] || q.is_prime || next
q*q > x || (f = mtest(m, q)) && break
} << 1..Inf
say (f ? "M#{m} is composite with factor #{q}"
: "M#{m} is prime")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,184 ⟶ 3,343:
M929 is composite with factor 13007
</pre>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">import Foundation
 
extension BinaryInteger {
var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
 
let max = Self(ceil((Double(self).squareRoot())))
 
for i in stride(from: 2, through: max, by: 1) where self % i == 0 {
return false
}
 
return true
}
 
func modPow(exp: Self, mod: Self) -> Self {
guard exp != 0 else {
return 1
}
 
var res = Self(1)
var base = self % mod
var exp = exp
 
while true {
if exp & 1 == 1 {
res *= base
res %= mod
}
 
if exp == 1 {
return res
}
 
exp >>= 1
base *= base
base %= mod
}
}
}
 
func mFactor(exp: Int) -> Int? {
for k in 0..<16384 {
let q = 2*exp*k + 1
 
if !q.isPrime {
continue
} else if q % 8 != 1 && q % 8 != 7 {
continue
} else if 2.modPow(exp: exp, mod: q) == 1 {
return q
}
}
 
return nil
}
 
print(mFactor(exp: 929)!)
</syntaxhighlight>
 
{{out}}
 
<pre>13007</pre>
 
=={{header|Tcl}}==
For <code>primes::is_prime</code> see [[Prime decomposition#Tcl]]
<langsyntaxhighlight lang="tcl">proc int2bits {n} {
binary scan [binary format I1 $n] B* binstring
return [split [string trimleft $binstring 0] ""]
Line 2,231 ⟶ 3,460:
} else {
puts "no factor found for M$exp"
}</langsyntaxhighlight>
 
 
=={{header|TI-83 BASIC}}==
Line 2,238 ⟶ 3,466:
{{works with|TI-83 BASIC|TI-84Plus 2.55MP}}
The program uses the new remainder function from OS 2.53MP, if not available it can be replaced by:
<langsyntaxhighlight lang="ti83b">remainder(A,B) equivalent to iPart(B*fPart(A/B))</langsyntaxhighlight>Due to several problems, no Goto has been used. As a matter of fact the version is clearer.
<langsyntaxhighlight lang="ti83b">Prompt Q
1→K:0→T
While K≤2^20 and T=0
Line 2,271 ⟶ 3,499:
End
If T=0:0→F
Disp Q,F</langsyntaxhighlight>
{{in}}
<pre>
Line 2,284 ⟶ 3,512:
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">Print "A factor of M929 is "; FUNC(_FNmersenne_factor(929))
Print "A factor of M937 is "; FUNC(_FNmersenne_factor(937))
 
Line 2,337 ⟶ 3,565:
Next
 
Return (d@)</langsyntaxhighlight>
{{out}}
<pre>A factor of M929 is 13007
Line 2,343 ⟶ 3,571:
 
0 OK, 0:123</pre>
 
=={{header|VBScript}}==
{{trans|REXX}}
<langsyntaxhighlight lang="vb">' Factors of a Mersenne number
for i=1 to 59
z=i
Line 2,407 ⟶ 3,636:
loop
testM=0
end function</langsyntaxhighlight>
{{out}}
<pre>
Line 2,432 ⟶ 3,661:
{{trans|BBC BASIC}}
{{works with|Visual Basic|VB6 Standard}}
<langsyntaxhighlight lang="vb">Sub mersenne()
Dim q As Long, k As Long, p As Long, d As Long
Dim factor As Long, i As Long, y As Long, z As Long
Line 2,467 ⟶ 3,696:
okfactor:
Debug.Print "M" & q, "factor=" & factor
End Sub</langsyntaxhighlight>
{{Out}}
<pre>
M47 factor=2351
</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="go">import math
const qlimit = int(2e8)
fn main() {
mtest(31)
mtest(67)
mtest(929)
}
fn mtest(m int) {
// the function finds odd prime factors by
// searching no farther than sqrt(N), where N = 2^m-1.
// the first odd prime is 3, 3^2 = 9, so M3 = 7 is still too small.
// M4 = 15 is first number for which test is meaningful.
if m < 4 {
println("$m < 4. M$m not tested.")
return
}
flimit := math.sqrt(math.pow(2, f64(m)) - 1)
mut qlast := 0
if flimit < qlimit {
qlast = int(flimit)
} else {
qlast = qlimit
}
mut composite := []bool{len: qlast+1}
sq := int(math.sqrt(f64(qlast)))
loop:
for q := int(3); ; {
if q <= sq {
for i := q * q; i <= qlast; i += q {
composite[i] = true
}
}
q8 := q % 8
if (q8 == 1 || q8 == 7) && mod_pow(2, m, q) == 1 {
println("M$m has factor $q")
return
}
for {
q += 2
if q > qlast {
break loop
}
if !composite[q] {
break
}
}
}
println("No factors of M$m found.")
}
// base b to power p, mod m
fn mod_pow(b int, p int, m int) int {
mut pow := i64(1)
b64 := i64(b)
m64 := i64(m)
mut bit := u32(30)
for 1<<bit&p == 0 {
bit--
}
for {
pow *= pow
if 1<<bit&p != 0 {
pow *= b64
}
pow %= m64
if bit == 0 {
break
}
bit--
}
return int(pow)
}</syntaxhighlight>
{{out}}
<pre>
No factors of M31 found.
M67 has factor 193707721
M929 has factor 13007
</pre>
 
=={{header|Wren}}==
{{trans|JavaScript}}
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./math" for Int
import "./fmt" for Conv, Fmt
 
var trialFactor = Fn.new { |base, exp, mod|
var square = 1
var bits = Conv.itoa(exp, 2).toList
var ln = bits.count
for (i in 0...ln) {
square = square * square * (bits[i] == "1" ? base : 1) % mod
}
return square == 1
}
 
var mersenneFactor = Fn.new { |p|
var limit = (2.pow(p) - 1).sqrt.floor
var k = 1
while ((2*k*p - 1) < limit) {
var q = 2*k*p + 1
if (Int.isPrime(q) && (q%8 == 1 || q%8 == 7) && trialFactor.call(2, p, q)) {
return q // q is a factor of 2^p - 1
}
k = k + 1
}
return null
}
 
var m = [3, 5, 11, 17, 23, 29, 31, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929]
for (p in m) {
var f = mersenneFactor.call(p)
Fmt.write("2^$3d - 1 is ", p)
if (f) {
Fmt.print("composite (factor $d)", f)
} else {
System.print("prime")
}
}</syntaxhighlight>
 
{{out}}
<pre>
2^ 3 - 1 is prime
2^ 5 - 1 is prime
2^ 11 - 1 is composite (factor 23)
2^ 17 - 1 is prime
2^ 23 - 1 is composite (factor 47)
2^ 29 - 1 is composite (factor 233)
2^ 31 - 1 is prime
2^ 37 - 1 is composite (factor 223)
2^ 41 - 1 is composite (factor 13367)
2^ 43 - 1 is composite (factor 431)
2^ 47 - 1 is composite (factor 2351)
2^ 53 - 1 is composite (factor 6361)
2^ 59 - 1 is composite (factor 179951)
2^ 67 - 1 is composite (factor 193707721)
2^ 71 - 1 is composite (factor 228479)
2^ 73 - 1 is composite (factor 439)
2^ 79 - 1 is composite (factor 2687)
2^ 83 - 1 is composite (factor 167)
2^ 97 - 1 is composite (factor 11447)
2^929 - 1 is composite (factor 13007)
</pre>
 
=={{header|zkl}}==
{{trans|EchoLisp}}
<syntaxhighlight lang="zkl">var [const] BN=Import("zklBigNum"); // libGMP
 
// M = 2^P - 1 , P prime
// Look for a prime divisor q such as:
// q < M.sqrt(), q = 1 or 7 modulo 8, q = 1 + 2kP
// q is divisor if 2.powmod(P,q) == 1
// m-divisor returns q or False
fcn m_divisor(P){
// must limit the search as M.sqrt() may be HUGE and I'm slow
maxPrime:='wrap{ BN(2).pow(P).sqrt().min(0d5_000_000) };
t,b2:=BN(0),BN(2); // so I can do some in place BigInt math
foreach q in (maxPrime(P*2)){ // 0..maxPrime -1, faster than just odd #s
if((q%8==1 or q%8==7) and t.set(q).probablyPrime() and
b2.powm(P,q)==1) return(q);
}
False
}</syntaxhighlight>
<syntaxhighlight lang="zkl">m_divisor(929).println(); // 13007
m_divisor(4423).println(); // False
(BN(2).pow(4423) - 1).probablyPrime().println(); // True</syntaxhighlight>
{{out}}
<pre>
13007
False
True
</pre>
2,503

edits