Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*******************************************************************************
 * $Id: $
 * Copyright (c) 2009-2010 Tim Tiemens.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * 
 * Contributors:
 *     Tim Tiemens - initial API and implementation
 ******************************************************************************/

import java.math.BigInteger;

import java.security.SecureRandom;
import java.util.Random;

public class Main {
    private static boolean passesMillerRabin(BigInteger us, int iterations, Random rnd) {
        final BigInteger ONE = BigInteger.ONE;
        final BigInteger TWO = BigInteger.valueOf(2);
        // Find a and m such that m is odd and this == 1 + 2**a * m
        BigInteger thisMinusOne = us.subtract(ONE);
        BigInteger m = thisMinusOne;
        int a = m.getLowestSetBit();
        m = m.shiftRight(a);

        // Do the tests
        if (rnd == null) {
            rnd = new SecureRandom();
        }
        for (int i = 0; i < iterations; i++) {
            // Generate a uniform random on (1, this)
            BigInteger b;
            do {
                b = new BigInteger(us.bitLength(), rnd);
            } while (b.compareTo(ONE) <= 0 || b.compareTo(us) >= 0);

            int j = 0;
            BigInteger z = b.modPow(m, us);
            while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
                if (j > 0 && z.equals(ONE) || ++j == a)
                    return false;
                z = z.modPow(TWO, us);
            }
        }
        return true;
    }
}