Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Updates n to its p-th power modulo m.
- *
- * @param n
- * number to be raised to a power
- * @param p
- * the power
- * @param m
- * the modulus
- * @updates n
- * @requires m > 1
- * @ensures n = #n ^ (p) mod m
- */
- public static void powerMod(NaturalNumber n, NaturalNumber p,
- NaturalNumber m) {
- assert m.compareTo(new NaturalNumber2(1)) > 0 : "Violation of: m > 1";
- /*
- * Use the fast-powering algorithm as previously discussed in class,
- * with the additional feature that every multiplication is followed
- * immediately by "reducing the result modulo m"
- */
- // TODO - fill in body
- NaturalNumber mod = new NaturalNumber2();
- mod = p.divide(new NaturalNumber2(2));
- if (p.equals(0)) {
- n.copyFrom(new NaturalNumber2(1));
- } else if (mod.isZero()) { //if p is even
- p.divide(new NaturalNumber2(2));
- p.multiply(new NaturalNumber2(2));
- } else if (!mod.isZero()) { //if p is odd
- p.divide(new NaturalNumber2(2));
- p.multiply(new NaturalNumber2(2));
- p.add(new NaturalNumber2(1));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement