Skip to content

Instantly share code, notes, and snippets.

@ZakTaccardi
Created November 5, 2014 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZakTaccardi/ada495f5216c30568ce7 to your computer and use it in GitHub Desktop.
Save ZakTaccardi/ada495f5216c30568ce7 to your computer and use it in GitHub Desktop.
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.
/**
* 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