Barrett reduction algorithm

https://www.nayuki.io/page/barrett-reduction-algorithm

某些rsa算法中会用到,核心原理通过乘法,减法和移位运算代替长除,提高大数取模的运算速度。

(* 
 * Barrett reduction algorithm (Mathematica)
 * 
 * Copyright (c) 2019 Project Nayuki
 * All rights reserved. Contact Nayuki for licensing.
 * https://www.nayuki.io/page/barrett-reduction-algorithm
 *)


(*---- User inputs ----*)

n = 8315;  (* The modulus *)
x = 28298572;  (* Number to reduce *)


(*---- The computation ----*)

BarrettReduce[x_, n_] := Block[{k, r, t},
    If[!IntegerQ[n] || n < 3, Abort[]];
    If[!IntegerQ[x] || !(0 <= x < n^2), Abort[]];
    
    k = Ceiling[Log[2, n]];
    r = Floor[4^k / n];
    t = x - Floor[x * r / 4^k] * n;
    If[t < n, t, t - n]]

(* Self-check *)
Print[BarrettReduce[x, n]]
Print[Mod[x, n]]
Print[BarrettReduce[x, n] == Mod[x, n]]  (* Must be true *)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值