Returns the prime-numbers number is divisible by without remainder Optimizing this function possibly could boost the overall process - Java java.lang

Java examples for java.lang:int prime

Description

Returns the prime-numbers number is divisible by without remainder Optimizing this function possibly could boost the overall process

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    /**//w  w w.j av  a2 s. c o  m
     * Returns the prime-numbers <b>number</b> is divisible by without remainder
     * Optimizing this function possibly could boost the overall process
     * @param number
     * @return An array of Primefactors for <b>number</b> in ascending order
     */
    public static Long[] getPrimeDivisors(long number) {
        if (number == 1l || number == 0l)
            return new Long[] {};
        if (isPrime(number))
            return new Long[] { number };

        List<Long> divisors = new ArrayList<>(0);

        for (long current = number / 2l; current > 1l; current--) {
            if (isDivisibleRemainderless(number, current)
                    && isPrime(current))
                divisors.add(current);
        }

        Collections.reverse(divisors);

        return divisors.toArray(new Long[divisors.size()]);
    }

    /**
     * Finds out if <b>number</b> is a prime-number
     * @param number
     * @return TRUE if prime
     */
    public static boolean isPrime(long number) {
        boolean result = true;

        for (long current = number / 2; current > 1; current--) {
            if ((number / current) * current == number) {
                result = false;
                break;
            }
        }

        return result;
    }

    /**
     * Convenience function,
     * returns TRUE if <b>number</b> is divisible by <b>i</b> without remainder
     * @param number
     * @param i
     * @return TRUE if <b>number</b> is divisible by <b>i</b> without remainder
     */
    public static boolean isDivisibleRemainderless(long number, long i) {
        return number % i == 0;
    }
}

Related Tutorials