September Morn Update

This commit is contained in:
Ingy döt Net 2019-09-12 10:33:56 -07:00
parent 4e2d22a71d
commit aac6731f2c
6856 changed files with 141342 additions and 21127 deletions

View file

@ -1,11 +1,53 @@
public static long fact(final int n) {
if (n < 0) {
System.err.println("No negative numbers");
return 0;
package programas;
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.util.Scanner;
public class IterativeFactorial {
public BigInteger factorial(BigInteger n) {
if ( n == null ) {
throw new IllegalArgumentException();
}
long ans = 1;
for (int i = 1; i <= n; i++) {
ans *= i;
else if ( n.signum() == - 1 ) {
// negative
throw new IllegalArgumentException("Argument must be a non-negative integer");
}
return ans;
else {
BigInteger factorial = BigInteger.ONE;
for ( BigInteger i = BigInteger.ONE; i.compareTo(n) < 1; i = i.add(BigInteger.ONE) ) {
factorial = factorial.multiply(i);
}
return factorial;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BigInteger number, result;
boolean error = false;
System.out.println("FACTORIAL OF A NUMBER");
do {
System.out.println("Enter a number:");
try {
number = scanner.nextBigInteger();
result = new IterativeFactorial().factorial(number);
error = false;
System.out.println("Factorial of " + number + ": " + result);
}
catch ( InputMismatchException e ) {
error = true;
scanner.nextLine();
}
catch ( IllegalArgumentException e ) {
error = true;
scanner.nextLine();
}
}
while ( error );
scanner.close();
}
}

View file

@ -1,7 +1,56 @@
public static long fact(final int n) {
if (n < 0){
System.err.println("No negative numbers");
return 0;
package programas;
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.util.Scanner;
public class RecursiveFactorial {
public BigInteger factorial(BigInteger n) {
if ( n == null ) {
throw new IllegalArgumentException();
}
return (n < 2) ? 1 : n * fact(n - 1);
else if ( n.equals(BigInteger.ZERO) ) {
return BigInteger.ONE;
}
else if ( n.signum() == - 1 ) {
// negative
throw new IllegalArgumentException("Argument must be a non-negative integer");
}
else {
return n.equals(BigInteger.ONE)
? BigInteger.ONE
: factorial(n.subtract(BigInteger.ONE)).multiply(n);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BigInteger number, result;
boolean error = false;
System.out.println("FACTORIAL OF A NUMBER");
do {
System.out.println("Enter a number:");
try {
number = scanner.nextBigInteger();
result = new RecursiveFactorial().factorial(number);
error = false;
System.out.println("Factorial of " + number + ": " + result);
}
catch ( InputMismatchException e ) {
error = true;
scanner.nextLine();
}
catch ( IllegalArgumentException e ) {
error = true;
scanner.nextLine();
}
}
while ( error );
scanner.close();
}
}