Advertisement
Guest User

Untitled

a guest
Aug 1st, 2015
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.PrintStream;
  4. import java.util.Date;
  5. import java.math.BigInteger;
  6.  
  7. public class Fibonacci {
  8.  
  9. public static void main(String[] args) {
  10. int length, starting = 1;
  11. try {
  12. if (args.length < 1 || args.length > 2) {
  13. System.out.println("Invalid number of arguments!");
  14. System.out.println("fibonacci <length> [initial]");
  15. return;
  16. }
  17. length = Integer.parseInt(args[0]);
  18. if (args.length >= 2)
  19. starting = Integer.parseInt(args[1]);
  20. if (length <= 0) {
  21. System.out.println("Length must be at least one!");
  22. return;
  23. }
  24. } catch (NumberFormatException ex) {
  25. System.out.println("Not a valid integer!");
  26. return;
  27. }
  28.  
  29. BigInteger[] results = new BigInteger[length];
  30. results[0] = BigInteger.ZERO;
  31. if (length > 1)
  32. results[1] = BigInteger.valueOf(starting);
  33.  
  34. System.out.println("Starting calculation...");
  35. double startingTime = new Date().getTime();
  36.  
  37. for (int i = 2; i < length; i++)
  38. results[i] = results[i - 1].add(results[i - 2]);
  39.  
  40. double endingTime = new Date().getTime();
  41. System.out.println("Calculation completed in " + String.format("%.3f", (endingTime - startingTime) * 0.001) + " second(s).");
  42. System.out.println("Results:");
  43.  
  44. for (BigInteger i : results)
  45. System.out.print(i.toString() + " ");
  46.  
  47. boolean writeSuccess = false;
  48. while (!writeSuccess) {
  49. System.out.println("\nInput a name for the results file (Leave blank to skip).");
  50. String name = System.console().readLine();
  51. if (name.isEmpty())
  52. writeSuccess = true;
  53. else {
  54. System.out.println("Attempting to write file " + name + ".");
  55. try {
  56. PrintStream writeOut = new PrintStream(new FileOutputStream(new File(name)));
  57. for (BigInteger i : results)
  58. writeOut.println(i.toString());
  59. writeOut.close();
  60. writeSuccess = true;
  61. } catch (Throwable th) {
  62. System.out.println("Error whilst writing file!");
  63. th.printStackTrace();
  64. }
  65. }
  66. }
  67.  
  68. }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement