Hello! Tell me by code that you can still add or alter? the program that calculates the factorial of the natural number n, which the user will enter from the keyboard.

How else can I remove 1 if, for example, I enter a negative number there it gives me "You entered negative factorial!", But it gives 1 over it?

public class Test { public static void main(String args[]) { int n; do { Scanner scan = new Scanner(System.in); System.out.print("Введите факториал натурально числа n : "); n = scan.nextInt(); int result = 1; for (int i = 2; i <= n; i++) result *= i; System.out.println(result); if (n == 0 || n == 1) System.out.println(result); if(n < 0) System.out.println("Вы ввели отрицательный факториал!"); } while (n < 0);{System.out.println("Конец");} } } 
  • one
    And what for ??? In this case, the recursion and memory eats more and the speed of her work will be less. Not to mention that StackOverflow can be observed when using it. private static long factor1 (long p) {return (p == 1? 1: p * factor1 (p - 1)); } private static long factor2 (long p) {long res = 1; for (; p> 0; p--) res * = p; return res; } And the fact that the turtles code itself is no good, cy6erGn0m said. - Dex
  • one
    "how to write factorial correctly" probably one of the most common mistakes in programming books is to demonstrate the work of recursion using the example of calculating factorial where recursion is not needed at all (well, that is, if the language allows you to write cycles). - yozh
  • so you can judge about everything you want, and with such arguments, recursion is not where it is needed at all, but this is just a small example of recursion, where the arguments about "more memory and speed of work" are not coded at all, IMHO. - Gorets

2 answers 2

So you first make a check for negative input, and then consider factorial in other cases. Come on, think about it. Stop compiling. This has nothing to do with writing essays;)

And why System.out.println ("End"); Are you stuck in braces?

And why is the condition in do .. while so strange?

And why in case of 0 and 1 you print the result twice?

  • Thanks for the very good advice, found the answer to your question! - turtles
  • Tell me, please, can I change your answer by adding a full code sample to it? - diraria
  int y=1; int n=8; for (int i=1; i<=n; i++){ y=y*i; } System.out.print(n+"!="); System.out.print(y);