Modular exponentiation: Difference between revisions
m
syntax highlighting fixup automation
(→{{header|Haskell}}: Added mod=1 case and improved readability by moving final expression into the pattern match and introducing where variables) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 16:
{{trans|D}}
<
BigInt result = 1
Line 29:
print(pow_mod(BigInt(‘2988348162058574136915891421498819466320163312926952423791023078876139’),
BigInt(‘2351399303373464486466122544523690094744975233415544072992656881240319’),
BigInt(10) ^ 40))</
{{out}}
Line 40:
Using the big integer implementation from a cryptographic library [https://github.com/cforler/Ada-Crypto-Library/].
<
procedure Mod_Exp is
Line 65:
Ada.Text_IO.Put("A**B (mod 10**40) = ");
Ada.Text_IO.Put_Line(LN.Utils.To_String(LN.Mod_Utils.Pow((+A), (+B), M)));
end Mod_Exp;</
{{out}}
Line 73:
The code below uses Algol 68 Genie which provides arbitrary precision arithmetic for LONG LONG modes.
<
BEGIN
PR precision=1000 PR
Line 97:
printf (($"Last 40 digits = ", 40dl$, mod power (a, b, m)))
END
</syntaxhighlight>
{{out}}
Line 105:
=={{header|Arturo}}==
<
b: 2351399303373464486466122544523690094744975233415544072992656881240319
loop [40 80 180 888] 'm ->
print ["(a ^ b) % 10 ^" m "=" powmod a b 10^m]</
{{out}}
Line 120:
=={{header|AutoHotkey}}==
{{libheader|MPL}}
<
#SingleInstance, Force
SetBatchLines, -1
Line 145:
msgbox % MP_DEC(result)
Return</
{{out}}
<pre>1527229998585248450016808958343740453059</pre>
Line 152:
{{works with|BBC BASIC for Windows}}
Uses the Huge Integer Math & Encryption library.
<
PROC_himeinit("")
Line 160:
h1% = 1 : h2% = 2 : h3% = 3 : h4% = 4
SYS `hi_PowMod`, ^h1%, ^h2%, ^h3%, ^h4%
PRINT FN_higetdec(4)</
{{out}}
<pre>
Line 168:
=={{header|Bracmat}}==
{{trans|Icon_and_Unicon}}
<
= base exponent modulus result
. !arg:(?base,?exponent,?modulus)
Line 195:
)
& out$("last 40 digits = " mod-power$(!a,!b,10^40))
)</
{{out}}
<pre>last 40 digits = 1527229998585248450016808958343740453059</pre>
Line 202:
Given numbers are too big for even 64 bit integers, so might as well take the lazy route and use GMP:
{{libheader|GMP}}
<
int main()
Line 226:
return 0;
}</
Output:
<pre>
Line 234:
=={{header|C sharp}}==
We can use the built-in function from BigInteger.
<
using System.Numerics;
Line 245:
Console.WriteLine(BigInteger.ModPow(a, b, m));
}
}</
{{out}}
<pre>
Line 253:
=={{header|C++}}==
{{libheader|Boost}}
<
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/integer.hpp>
Line 265:
std::cout << powm(a, b, pow(cpp_int(10), 40)) << '\n';
return 0;
}</
{{out}}
Line 273:
=={{header|Clojure}}==
<
(defn m* [p q] (mod (* p q) m))
(loop [b b, e e, x 1]
(if (zero? e) x
(if (even? e) (recur (m* b b) (/ e 2) x)
(recur (m* b b) (quot e 2) (m* b x))))))</
<
(defn modpow
" b^e mod m (using Java which solves some cases the pure clojure method has to be modified to tackle--i.e. with large b & e and
calculation simplications when gcd(b, m) == 1 and gcd(e, m) == 1) "
[b e m]
(.modPow (biginteger b) (biginteger e) (biginteger m)))</
=={{header|Common Lisp}}==
<
"Return BASE raised to the POWER, modulo DIVISOR.
This function is faster than (MOD (EXPT BASE POWER) DIVISOR), but
Line 305:
(let ((a 2988348162058574136915891421498819466320163312926952423791023078876139)
(b 2351399303373464486466122544523690094744975233415544072992656881240319))
(format t "~A~%" (rosetta-mod-expt a b (expt 10 40))))</
{{works with|CLISP}}
<
(let ((a 2988348162058574136915891421498819466320163312926952423791023078876139)
(b 2351399303373464486466122544523690094744975233415544072992656881240319))
(format t "~A~%" (mod-expt a b (expt 10 40))))</
===Implementation with LOOP===
<
(loop with c = 1 while (plusp n) do
(if (oddp n) (setf c (mod (* a c) m)))
(setf n (ash n -1))
(setf a (mod (* a a) m))
finally (return c)))</
=={{header|Crystal}}==
<
module Integer
Line 346:
m = 10.to_big_i ** 40
puts a.powmod(b, m)</
{{out}}
Line 354:
{{trans|Icon_and_Unicon}}
Compile this module with <code>-version=modular_exponentiation</code> to see the output.
<
private import std.bigint;
Line 383:
"4744975233415544072992656881240319"),
BigInt(10) ^^ 40).writeln;
}</
{{out}}
<pre>1527229998585248450016808958343740453059</pre>
=={{header|Dc}}==
<syntaxhighlight lang
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
Line 394:
{{Trans|C#}}
Thanks for Rudy Velthuis, BigIntegers library [https://github.com/rvelthuis/DelphiBigNumbers].
<syntaxhighlight lang="delphi">
program Modular_exponentiation;
Line 412:
Writeln(BigInteger.ModPow(a, b, m).ToString);
readln;
end.</
{{out}}
<pre>1527229998585248450016808958343740453059</pre>
=={{header|EchoLisp}}==
<
(lib 'bigint)
Line 440:
(xpowmod a b m)
→ 1527229998585248450016808958343740453059
</syntaxhighlight>
=={{header|Emacs Lisp}}==
{{libheader|Calc}}
<
(b "2351399303373464486466122544523690094744975233415544072992656881240319"))
;; "$ ^ $$ mod (10 ^ 40)" performs modular exponentiation.
;; "unpack(-5, x)_1" unpacks the integer from the modulo form.
(message "%s" (calc-eval "unpack(-5, $ ^ $$ mod (10 ^ 40))_1" nil a b)))</
=={{header|Erlang}}==
<
%%% For details of the algorithms used see
%%% https://en.wikipedia.org/wiki/Modular_exponentiation
Line 497:
binary_exp(10,40)).
</syntaxhighlight>
<pre>
34> modexp_rosetta:test().
Line 506:
=={{header|F_Sharp|F#}}==
<
let rec loop a b c =
if b = 0I then c else
Line 517:
let b = 2351399303373464486466122544523690094744975233415544072992656881240319I
printfn "%A" (expMod a b (10I**40)) // -> 1527229998585248450016808958343740453059
0</
=={{header|Factor}}==
<
2988348162058574136915891421498819466320163312926952423791023078876139
2351399303373464486466122544523690094744975233415544072992656881240319
10 40 ^
^mod .</
{{out}}
<pre>
Line 531:
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
'From first principles (No external library)
Line 794:
</syntaxhighlight>
<pre>
Result:
Line 804:
=={{header|Frink}}==
<
b = 2351399303373464486466122544523690094744975233415544072992656881240319
println[modPow[a,b,10^40]]</
{{out}}
Line 813:
=={{header|GAP}}==
<
a := 2988348162058574136915891421498819466320163312926952423791023078876139;
b := 2351399303373464486466122544523690094744975233415544072992656881240319;
Line 833:
end;
PowerModAlt(a, b, 10^40);</
=={{header|gnuplot}}==
<
powm(b, e, m) = _powm(b, e, m, 1)
# Usage
print powm(2, 3453, 131)
# Where b is the base, e is the exponent, m is the modulus, i.e.: b^e mod m</
=={{header|Go}}==
<
import (
Line 862:
r.Exp(a, b, m)
fmt.Println(r)
}</
{{out}}
<pre>
Line 869:
=={{header|Groovy}}==
<
2351399303373464486466122544523690094744975233415544072992656881240319,
10000000000000000000000000000000000000000)</
Ouput:
<pre>1527229998585248450016808958343740453059</pre>
=={{header|Haskell}}==
<
modPow :: Integer -> Integer -> Integer -> Integer -> Integer
modPow b e 1 r = 0
Line 892:
(10 ^ 40)
1)
</syntaxhighlight>
{{out}}
<pre>1527229998585248450016808958343740453059</pre>
or in terms of ''until'':
<
powerMod b e m = x
where
Line 917:
2988348162058574136915891421498819466320163312926952423791023078876139
2351399303373464486466122544523690094744975233415544072992656881240319
(10 ^ 40)</
{{Out}}
<pre>1527229998585248450016808958343740453059</pre>
Line 923:
=={{header|Icon}} and {{header|Unicon}}==
This uses the exponentiation procedure from [[RSA_code#Icon_and_Unicon|RSA Code]] an example of the right to left binary method.
<
a := 2988348162058574136915891421498819466320163312926952423791023078876139
b := 2351399303373464486466122544523690094744975233415544072992656881240319
Line 939:
}
return result
end</
{{out}}
Line 945:
=={{header|J}}==
'''Solution''':<syntaxhighlight lang
'''Example''':<
b =: 2351399303373464486466122544523690094744975233415544072992656881240319x
m =: 10^40x
a m&|@^ b
1527229998585248450016808958343740453059</
'''Discussion''': The phrase <tt>a m&|@^ b</tt> is the natural expression of <tt>a^b mod m</tt> in J, and is recognized by the interpreter as an opportunity for optimization, by [http://www.jsoftware.com/help/dictionary/special.htm#recognized%20phrase avoiding the exponentiation].
Line 957:
<code>java.math.BigInteger.modPow</code> solves this task. Inside [[OpenJDK]], [http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/f097ca2434b1/src/share/classes/java/math/BigInteger.java BigInteger.java] implements <code>BigInteger.modPow</code> with a fast algorithm from [http://philzimmermann.com/EN/bnlib/index.html Colin Plumb's bnlib]. This "window algorithm" caches odd powers of the base, to decrease the number of squares and multiplications. It also exploits both the Chinese remainder theorem and the [[Montgomery reduction]].
<
public class PowMod {
Line 969:
System.out.println(a.modPow(b, m));
}
}</
{{out}}
<pre>1527229998585248450016808958343740453059</pre>
Line 977:
We can use the built-in <code>powermod</code> function with the built-in <code>BigInt</code> type (based on GMP):
<
b = 2351399303373464486466122544523690094744975233415544072992656881240319
m = big(10) ^ 40
@show powermod(a, b, m)</
{{out}}
Line 986:
=={{header|Kotlin}}==
<
import java.math.BigInteger
Line 995:
val m = BigInteger.TEN.pow(40)
println(a.modPow(b, m))
}</
{{out}}
Line 1,006:
Following scheme
<
We will call the lib_BN library for big numbers:
Line 1,035:
{BN.pow 10 40}}
-> 1527229998585248450016808958343740453059 // 3300ms
</syntaxhighlight>
=={{header|Maple}}==
<
b := 2351399303373464486466122544523690094744975233415544072992656881240319:
a &^ b mod 10^40;</
{{out}}
<pre>1527229998585248450016808958343740453059</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
b = 2351399303373464486466122544523690094744975233415544072992656881240319;
m = 10^40;
PowerMod[a, b, m]
-> 1527229998585248450016808958343740453059</
=={{header|Maxima}}==
<
b: 2351399303373464486466122544523690094744975233415544072992656881240319$
power_mod(a, b, 10^40);
/* 1527229998585248450016808958343740453059 */</
=={{header|Nim}}==
{{libheader|bigints}}
<
proc powmod(b, e, m: BigInt): BigInt =
Line 1,076:
b = initBigInt("2351399303373464486466122544523690094744975233415544072992656881240319")
echo powmod(a, b, 10.pow 40)</
{{out}}
<pre>1527229998585248450016808958343740453059</pre>
Line 1,084:
Using the zarith library:
<
let a = Z.of_string "2988348162058574136915891421498819466320163312926952423791023078876139" in
let b = Z.of_string "2351399303373464486466122544523690094744975233415544072992656881240319" in
Line 1,090:
Z.powm a b m
|> Z.to_string
|> print_endline</
{{out}}
<pre>1527229998585248450016808958343740453059</pre>
Line 1,098:
Usage : a b mod powmod
<
1 exponent dup ifZero: [ return ]
while ( dup 0 > ) [
dup isEven ifFalse: [ swap base * modulus mod swap ]
2 / base sq modulus mod ->base
] drop ;</
{{out}}
Line 1,119:
=={{header|ooRexx}}==
<
numeric digits 100
Line 1,140:
base = (base * base) // modulus
end
return result</
{{out}}
<pre>
Line 1,147:
=={{header|PARI/GP}}==
<
b=2351399303373464486466122544523690094744975233415544072992656881240319;
lift(Mod(a,10^40)^b)</
=={{header|Pascal}}==
Line 1,155:
{{libheader|GMP}}
A port of the C example using gmp.
<
uses
Line 1,180:
mpz_clear(m);
mpz_clear(r);
end.</
{{out}}
<pre>% ./ModularExponentiation
Line 1,188:
=={{header|Perl}}==
Calculating the result both with an explicit algorithm (borrowed from Raku example) and with a built-in available when the <code>use bigint</code> pragma is invoked. Note that <code>bmodpow</code> modifies the base value (here <code>$a</code>) while <code>expmod</code> does not.
<
sub expmod {
Line 1,205:
print expmod($a, $b, $m), "\n";
print $a->bmodpow($b, $m), "\n";</
{{out}}
<pre>1527229998585248450016808958343740453059
Line 1,214:
Already builtin as mpz_powm, but here is an explicit version
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 1,248:
<span style="color: #7060A8;">mpz_powm</span><span style="color: #0000FF;">(</span><span style="color: #000000;">result</span><span style="color: #0000FF;">,</span><span style="color: #000000;">base</span><span style="color: #0000FF;">,</span><span style="color: #000000;">exponent</span><span style="color: #0000FF;">,</span><span style="color: #000000;">modulus</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">result</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
Line 1,257:
=={{header|PHP}}==
<
$a = '2988348162058574136915891421498819466320163312926952423791023078876139';
$b = '2351399303373464486466122544523690094744975233415544072992656881240319';
$m = '1' . str_repeat('0', 40);
echo bcpowmod($a, $b, $m), "\n";</
{{out}}
<pre>1527229998585248450016808958343740453059</pre>
Line 1,267:
=={{header|PicoLisp}}==
The following function is taken from "lib/rsa.l":
<
(let M 1
(loop
Line 1,274:
(T (=0 (setq Y (>> 1 Y)))
M )
(setq X (% (* X X) N)) ) ) )</
Test:
<
2988348162058574136915891421498819466320163312926952423791023078876139
2351399303373464486466122544523690094744975233415544072992656881240319
10000000000000000000000000000000000000000 )
-> 1527229998585248450016808958343740453059</
=={{header|Prolog}}==
{{works with|SWI Prolog}}
SWI Prolog has a built-in function named powm for this purpose.
<
A = 2988348162058574136915891421498819466320163312926952423791023078876139,
B = 2351399303373464486466122544523690094744975233415544072992656881240319,
M is 10 ** 40,
P is powm(A, B, M),
writeln(P).</
{{out}}
Line 1,298:
=={{header|Python}}==
<
b = 2351399303373464486466122544523690094744975233415544072992656881240319
m = 10 ** 40
print(pow(a, b, m))</
{{out}}
<pre>1527229998585248450016808958343740453059</pre>
<
" Without using builtin function "
x = 1
Line 1,321:
b = 2351399303373464486466122544523690094744975233415544072992656881240319
m = 10 ** 40
print(power_mod(a, b, m))</
{{out}}
<pre>1527229998585248450016808958343740453059</pre>
Line 1,327:
=={{header|Quackery}}==
<
[ dup while
dup 1 & if
Line 1,341:
2988348162058574136915891421498819466320163312926952423791023078876139
2351399303373464486466122544523690094744975233415544072992656881240319
10 40 ** **mod echo</
{{out}}
Line 1,348:
=={{header|Racket}}==
<
#lang racket
(require math)
Line 1,355:
(define m (expt 10 40))
(modular-expt a b m)
</syntaxhighlight>
{{out}}
<pre>
Line 1,364:
(formerly Perl 6)
This is specced as a built-in, but here's an explicit version:
<syntaxhighlight lang="raku"
my $c = 1;
repeat while $b div= 2 {
Line 1,376:
2988348162058574136915891421498819466320163312926952423791023078876139,
2351399303373464486466122544523690094744975233415544072992656881240319,
10**40;</
{{out}}
<pre>1527229998585248450016808958343740453059</pre>
Line 1,389:
This REXX program code has code to automatically adjust the number of decimal digits to accommodate huge
<br>numbers which are computed when raising large numbers to some arbitrary power.
<
parse arg a b m /*obtain optional args from the CL*/
if a=='' | a=="," then a= 2988348162058574136915891421498819466320163312926952423791023078876139
Line 1,409:
if p // 2 then $= $ * x // mm /*is P odd? (is ÷ remainder ≡ 1?)*/
p= p % 2; x= x * x // mm /*halve P; calculate x² mod n */
end /*until*/; return $ /* [↑] keep mod'ing until P=zero.*/</
This REXX program makes use of '''LINESIZE''' REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console).
<br>The BIF is used to determine the width of a line separator (which are used to separate different outputs).
Line 1,431:
===version 2===
This REXX version handles only up to 100 decimal digits.
<
/* REXX Modular exponentiation */
Line 1,453:
base = (base * base) // modulus
end
return result</
{{out}}
<pre>
Line 1,461:
=={{header|Ruby}}==
===Built in since version 2.5.===
<
b = 2351399303373464486466122544523690094744975233415544072992656881240319
m = 10**40
puts a.pow(b, m)</
===Using OpenSSL standard library===
{{libheader|OpenSSL}}
<
a = 2988348162058574136915891421498819466320163312926952423791023078876139
b = 2351399303373464486466122544523690094744975233415544072992656881240319
m = 10 ** 40
puts a.to_bn.mod_exp(b, m)</
===Written in Ruby===
<
def mod_exp(n, e, mod)
fail ArgumentError, 'negative exponent' if e < 0
Line 1,485:
prod
end
</syntaxhighlight>
=={{header|Rust}}==
<
num = "0.2.0"
*/
Line 1,535:
base %= &m;
}
}</
'''Test code:'''
<
let (a, b, num_digits) = (
"2988348162058574136915891421498819466320163312926952423791023078876139",
Line 1,558:
println!("The last {} digits of\n{}\nto the power of\n{}\nare:\n{}",
num_digits, a, b, result);
}</
{{out}}
<pre>The last 40 digits of
Line 1,568:
=={{header|Scala}}==
<
val a = BigInt(
Line 1,575:
"2351399303373464486466122544523690094744975233415544072992656881240319")
println(a.modPow(b, BigInt(10).pow(40)))</
=={{header|Scheme}}==
<
(define (square n)
(* n n))
Line 1,594:
(mod-exp 2988348162058574136915891421498819466320163312926952423791023078876139
2351399303373464486466122544523690094744975233415544072992656881240319
(expt 10 40)))</
{{out}}
Line 1,606:
[http://seed7.sourceforge.net/libraries/bigint.htm#modPow%28in_var_bigInteger,in_var_bigInteger,in_bigInteger%29 modPow],
which does modular exponentiation.
<
include "bigint.s7i";
Line 1,614:
2351399303373464486466122544523690094744975233415544072992656881240319_,
10_ ** 40));
end func;</
{{out}}
Line 1,622:
The library bigint.s7i defines modPow with:
<
in var bigInteger: exponent, in bigInteger: modulus) is func
result
Line 1,638:
end while;
end if;
end func;</
Original source: [http://seed7.sourceforge.net/algorith/math.htm#modPow]
Line 1,644:
=={{header|Sidef}}==
Built-in:
<
2988348162058574136915891421498819466320163312926952423791023078876139,
2351399303373464486466122544523690094744975233415544072992656881240319,
10**40)</
User-defined:
<
var c = 1
do {
Line 1,657:
} while (b //= 2)
c
}</
{{out}}
<pre>
Line 1,670:
AttaSwift's BigInt has a built-in modPow method, but here we define a generic modPow.
<
func modPow<T: BinaryInteger>(n: T, e: T, m: T) -> T {
Line 1,700:
let b = BigInt("2351399303373464486466122544523690094744975233415544072992656881240319")
print(modPow(n: a, e: b, m: BigInt(10).power(40)))</
{{out}}
Line 1,712:
===Recursive===
<
# Algorithm from http://introcs.cs.princeton.edu/java/78crypto/ModExp.java.html
Line 1,724:
}
return $c
}</
Demonstrating:
<
set b 2351399303373464486466122544523690094744975233415544072992656881240319
set n [expr {10**40}]
puts [expr {modexp($a,$b,$n)}]</
{{out}}
<pre>
Line 1,736:
===Iterative===
<
proc modexp {a b n} {
for {set c 1} {$b} {set a [expr {$a*$a % $n}]} {
Line 1,745:
}
return $c
}</
Demonstrating:
<
set b 2351399303373464486466122544523690094744975233415544072992656881240319
set n [expr {10**40}]
puts [modexp $a $b $n]</
{{out}}
<pre>
Line 1,760:
From your system prompt:
<
2351399303373464486466122544523690094744975233415544072992656881240319
(expt 10 40)))'
1527229998585248450016808958343740453059</
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2011}}
<
Imports System.Numerics
Line 1,790:
Loop
Return result
End Function 'ModPowBig</
{{out}}
<pre>
Line 1,798:
=={{header|Wren}}==
{{libheader|Wren-big}}
<
var a = BigInt.new("2988348162058574136915891421498819466320163312926952423791023078876139")
var b = BigInt.new("2351399303373464486466122544523690094744975233415544072992656881240319")
var m = BigInt.ten.pow(40)
System.print(a.modPow(b, m))</
{{out}}
Line 1,812:
=={{header|zkl}}==
Using the GMP big num library:
<
a:=BN("2988348162058574136915891421498819466320163312926952423791023078876139");
b:=BN("2351399303373464486466122544523690094744975233415544072992656881240319");
m:=BN(10).pow(40);
a.powm(b,m).println();
a.powm(b,m) : "%,d".fmt(_).println();</
{{out}}
<pre>
|