Skip to content

Instantly share code, notes, and snippets.

@phantamanta44
Created July 13, 2015 23:04
Show Gist options
  • Save phantamanta44/e13f57ef755caf9a751d to your computer and use it in GitHub Desktop.
Save phantamanta44/e13f57ef755caf9a751d to your computer and use it in GitHub Desktop.
Small challenge
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Date;
import java.math.BigInteger;
public class Fibonacci {
public static void main(String[] args) {
int length, starting = 1;
try {
if (args.length < 1 || args.length > 2) {
System.out.println("Invalid number of arguments!");
System.out.println("fibonacci <length> [initial]");
return;
}
length = Integer.parseInt(args[0]);
if (args.length >= 2)
starting = Integer.parseInt(args[1]);
if (length <= 0) {
System.out.println("Length must be at least one!");
return;
}
} catch (NumberFormatException ex) {
System.out.println("Not a valid integer!");
return;
}
BigInteger[] results = new BigInteger[length];
results[0] = BigInteger.ZERO;
if (length > 1)
results[1] = BigInteger.valueOf(starting);
System.out.println("Starting calculation...");
double startingTime = new Date().getTime();
for (int i = 2; i < length; i++)
results[i] = results[i - 1].add(results[i - 2]);
double endingTime = new Date().getTime();
System.out.println("Calculation completed in " + String.format("%.3f", (endingTime - startingTime) * 0.001) + " second(s).");
System.out.println("Results:");
for (BigInteger i : results)
System.out.print(i.toString() + " ");
boolean writeSuccess = false;
while (!writeSuccess) {
System.out.println("\nInput a name for the results file (Leave blank to skip).");
String name = System.console().readLine();
if (name.isEmpty())
writeSuccess = true;
else {
System.out.println("Attempting to write file " + name + ".");
try {
PrintStream writeOut = new PrintStream(new FileOutputStream(new File(name)));
for (BigInteger i : results)
writeOut.println(i.toString());
writeOut.close();
writeSuccess = true;
} catch (Throwable th) {
System.out.println("Error whilst writing file!");
th.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment