Skip to main content

Java - Calculate Factorial



This code snippet calculates the factorial of a number up to 20. Because of the large numbers it can't go higher then 20, 21 factorial is: 51.090.942.171.709.440.000. There are two methods in this code, one for calculating it with recursion and one non-recursive.


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Factorial {
    public static void main(String[] args) {
        System.out.println(factorialRecursion(20));
        System.out.println(factorial(20));
    }
    public static long factorialRecursion(long l) {
        if (l < 2)
            return 1;
        else
            return l * factorialRecursion(l - 1);
    }
    public static long factorial(int fact) {
        long result = 1;
         
        for (int i = 1; i <= fact; ++i) {
            result *= i;
        }
        return result;
    }
}


Output:
2432902008176640000
2432902008176640000

Comments

Popular posts from this blog

How To Install Age Of Empires 2: Forgotten Empires

There is a new unofficial expansion pack for Age of Empires 2 called Forgotten Empires. To install Forgotten Empires you need the original Age of Empires II "Age of Kings" and the official expansion pack "The Conquerors". When Age of Empires 2 came out I could play this game non stop for hours and with this new expansion pack it looks like that's still possible even though I'm not really much of a gamer ;). Features 5  brand new civilizations 30  new technologies 9  new units 1000  population limit 11  new maps 1  new building 2  new architecture sets 20  new scenario editor objects ?  new campaigns Full  unlimited  resolutions (Widescreen included) Install Make sure to have Age of Empires II: The Conquerors installed Download the installer exe | zip Unzip the file into your Age of Empires II Installation folder (typically C:\Program Files\Microsoft Games\Age of Empires II\) Select your ...

Block Spotify Ads

Spotify is a digital music service that gives you access to millions of songs without having to pay a penny.  Off couse you can pay so you don't have to listen to those ads anymore, but there is a free way to block Spotify ads. The best ad blocker at the moment is Blockify that mutes Spotify whenever it detects an audio ad. When the ad finished playing it will unmute Spotify and play your tracks. Blockify also adds customizable hotkeys to Spotify, so you can skip tracks, play, pause, shuffle, and change the volume with keyboard shortcuts. Features: Mutes Spotify whenever it detects an audio ad. Play your own MP3s during adverts. Control Spotify via keyboard hotkeys. Easy to use, totally portable. Unlike every other advert blocker, it doesn't rely on a list! Download Blockify