Returns falling sequential product of n elements starts from x - Java java.lang

Java examples for java.lang:Math Algorithm

Description

Returns falling sequential product of n elements starts from x

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        long x = 2;
        long n = 2;
        System.out.println(fallingFactorial(x, n));
    }//ww w.j  a  v  a 2  s .c  o m

    /**
     * Returns falling sequential product of n elements starts from x
     * @param x - first element in falling sequence
     * @param n - elements count in sequence
     * @return falling sequential product
     */
    public static long fallingFactorial(long x, long n) {
        if (x < 0 || n < 0)
            throw new IllegalArgumentException(
                    "x should be more or equals than 0 and n should be more than 0");
        if (x < n)
            throw new IllegalArgumentException("x should be more than n");
        if (x == 0 || n == 0)
            return 1;
        long fact = 1;
        long xEnd = x - n + 1;
        for (long l = n; l >= xEnd; l--) {
            fact *= l;
        }
        return fact;
    }
}

Related Tutorials