Created
November 5, 2014 19:27
-
-
Save ZakTaccardi/ada495f5216c30568ce7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
the below is command line output generated from the (further below) main method | |
Factorial of '31' is '738197504' | |
Factorial of '10' is '3628800' | |
Factorial of '5' is '120' | |
Factorial of '4' is '24' | |
Factorial of '3' is '6' | |
Factorial of '2' is '2' | |
Factorial of '1' is '1' | |
Factorial of '0' is '1' | |
Attempted factorial of '-1'. Factorials of negative integers are undefined. | |
Attempted factorial of '-2'. Factorials of negative integers are undefined. | |
Attempted factorial of '-8'. Factorials of negative integers are undefined. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Calculates factorial values. One thing this class doesn't do is handle large factorials appropriately. | |
* @author Zak Taccardi | |
*/ | |
public class FactorialMaker { | |
public static final int UNDEFINED_OPERATION = -1; | |
/** | |
* Calculates a factorial for a number | |
* @param num the int to do a factorial with | |
* @return the result of the factorial calculation. If the value is undefined, this method returns -1 | |
*/ | |
public static int doFactorial(int num){ | |
int r = 1; | |
if(num > 1) { | |
int i = num; | |
while (i > 1){ //no point running again when i == 1, because 'r' * 1 is always 'r' | |
r *= i; | |
i--; | |
} | |
printFactorial(num, r); | |
return r; | |
} else if (num == 0 || num == 1) { | |
printFactorial(num, r); | |
return 1; //0! and 1! are always 1 | |
} else if (num <= -1){ | |
System.out.println("Attempted factorial of '" + num +"'. Factorials of negative integers are undefined."); | |
return UNDEFINED_OPERATION; | |
} else | |
return UNDEFINED_OPERATION; | |
} | |
//handles basic printing do command line | |
private static void printFactorial(int initialValue, int result){ | |
System.out.println("Factorial of '" + initialValue + "' is '" + result + "'"); | |
} | |
public static void main(String [] args){ | |
doFactorial(31); | |
doFactorial(10); | |
doFactorial(5); | |
doFactorial(4); | |
doFactorial(3); | |
doFactorial(2); | |
doFactorial(1); | |
doFactorial(0); | |
doFactorial(-1); | |
doFactorial(-2); | |
doFactorial(-8); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment