Advertisement
jaVer404

level15.lesson12.bonus03

Aug 6th, 2015
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. package com.javarush.test.level15.lesson12.bonus03;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.math.BigInteger;
  7.  
  8. /* Факториал
  9. Написать метод, который вычисляет факториал - произведение всех чисел от 1 до введенного числа включая его.
  10. Пример: 4! = factorial(4) = 1*2*3*4 = 24
  11. 1. Ввести с консоли число меньше либо равно 150.
  12. 2. Реализовать функцию  factorial.
  13.  
  14. 3. Если введенное число меньше 0, то вывести 0.
  15. 0! = 1
  16. */
  17.  
  18. public class Solution {
  19.     public static void main(String[] args) throws IOException {
  20.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  21.  
  22.         int input = Integer.parseInt(reader.readLine());
  23.         reader.close();
  24.  
  25.         System.out.println(factorial(input));
  26.     }
  27.  
  28.     public static String factorial(int n) {
  29.         //add your code here
  30.         String output = "";
  31.         if (n < 0) {
  32.             output = "0";
  33.         }
  34.         else if (n == 0) {
  35.             output = "1";
  36.         }
  37.         else {
  38.             BigInteger temp = BigInteger.valueOf(1);
  39.             for (int i = 1; i <= n; i++) {
  40.                 temp = temp.multiply(BigInteger.valueOf(i));
  41.             }
  42.             output = temp.toString();
  43.         }
  44.         return output;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement