Java BigInteger Value Check isFermatNumber(BigInteger f)

Here you can find the source of isFermatNumber(BigInteger f)

Description

Method to check if a given number is a Fermat number.

License

Open Source License

Parameter

Parameter Description
f a checking number

Return

true iff there exists a non-negative integer n such that f = 22^n + 1

Declaration

public static boolean isFermatNumber(BigInteger f) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.math.BigInteger;

public class Main {
    /**//from w w w .  jav a  2 s. co  m
     * Method to check if a given number is a Fermat number. Linear time.
     * https://en.wikipedia.org/wiki/Fermat_number
     * @param f a checking number
     * @return true iff there exists a non-negative integer n such that f = 2<sup>2^n</sup> + 1
     */
    public static boolean isFermatNumber(BigInteger f) {
        if (f.signum() <= 0)
            return false;
        byte bytes[] = f.toByteArray();
        int bLength = bytes.length - 1;
        if (bLength == 0) {
            switch (bytes[0]) {
            case 3:
            case 5:
            case 17:
                return true;
            default:
                return false;
            }
        }
        // Checking if bLength is a power of 2.
        // http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two
        if ((bLength & (bLength - 1)) != 0)
            return false;
        if (bytes[0] != 1 || bytes[bLength] != 1)
            return false;
        for (int i = 1; i < bLength; i++)
            if (bytes[i] != 0)
                return false;
        return true;
    }
}

Related

  1. isBigger(final BigInteger big1, final BigInteger big2)
  2. isCovers(BigInteger covers, BigInteger value)
  3. isDefined(BigInteger no)
  4. isElementOfZn(BigInteger element, BigInteger n)
  5. isEven(BigInteger x)
  6. isGoodGaAndGb(BigInteger g_a, BigInteger p)
  7. isIn20PercentRange(BigInteger first, BigInteger second)
  8. isInRange(BigInteger in, int range, double eps)
  9. isInt(final BigInteger i)