Advertisement
mrAnderson33

Четвертая лаба Java

Dec 21st, 2017
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. package com.company;
  2.  
  3.  
  4. import java.math.BigInteger;
  5. import java.util.InputMismatchException;
  6. import java.util.Scanner;
  7.  
  8. public class Main
  9. {
  10.  
  11.     public static void main(String[] args)
  12.     {
  13.  
  14.         int num = 0;
  15.  
  16.         Scanner in = new Scanner(System.in);
  17.  
  18.         System.out.print("Please, enter a number for factorial: ");
  19.  
  20.         try
  21.         {
  22.            num = in.nextInt();
  23.         }
  24.         catch (InputMismatchException ex)
  25.         {
  26.             System.err.println("Error, you should enter a digit");
  27.             System.exit(1);
  28.  
  29.         }
  30.  
  31.         try
  32.         {
  33.           System.out.println("factorial("+ num +") = " +factorial(BigInteger.valueOf(num)));
  34.         }
  35.         catch (IllegalArgumentException ex)
  36.         {
  37.             System.err.println(ex.getMessage());
  38.             System.exit(2);
  39.         }
  40.  
  41.         System.out.print("Please, enter a number for fibonachi: ");
  42.  
  43.         try
  44.         {
  45.             num = in.nextInt();
  46.         }
  47.         catch (InputMismatchException ex)
  48.         {
  49.             System.err.println("Error, you should enter a digit");
  50.             System.exit(1);
  51.         }
  52.  
  53.         try
  54.         {
  55.             System.out.println("fibonachi №"+ num +" = " +fibonachi(num));
  56.         }
  57.         catch (IllegalArgumentException ex)
  58.         {
  59.             System.err.println(ex.getMessage());
  60.             System.exit(3);
  61.         }
  62.  
  63.     }
  64.  
  65.     public  static BigInteger factorial (BigInteger n)
  66.     {
  67.         if (n.compareTo(BigInteger.valueOf(0)) == -1)  throw new IllegalArgumentException("Error, number should be positive");
  68.         return ((n.compareTo(BigInteger.valueOf(0)) == 0)||(n.compareTo(BigInteger.valueOf(1))==0)) ? BigInteger.valueOf(1) : n.multiply(factorial( n.add(BigInteger.valueOf(-1))));
  69.     }
  70.  
  71.  
  72.  
  73.     public static BigInteger fibonachi(int n)
  74.     {
  75.         if(n < 0) throw new IllegalArgumentException("Error, number should be positive");
  76.  
  77.         BigInteger a = BigInteger.valueOf(0);
  78.         BigInteger b = BigInteger.valueOf(1);
  79.  
  80.         while (n--!=0)
  81.         {
  82.             BigInteger temp = b;
  83.             b=a.add(b);
  84.             a=temp;
  85.         }
  86.         return a;
  87.     }
  88.  
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement