0

Factorial - Java Help me to fix this please

Here is the question The factorial of a number N is equal to 1 * 2 * 3 * ... * N For example, the factorial of 5 is 1* 2 * 3 * 4 * 5 = 120. Create a program that takes a number from input and output the factorial of that number. This is my answer to this. But it's not taken as the correct answer and also not getting any error what's wrong with this code. help me to solve this import java.util.Scanner; class Demo{ public static void main(String[] args) { long fact = 1; Scanner sc = new Scanner(System.in); int x = sc.nextInt(); for(int i=1; i<=x; i++){ fact = fact * 1; } System.out.println(fact); } }

3rd Apr 2024, 5:31 PM
W.D.V Gunarathna
W.D.V Gunarathna - avatar
3 Answers
+ 4
Focus on the code inside the loop: fact = fact * 1 What is the result of multiplying fact by 1?
3rd Apr 2024, 5:42 PM
Brian
Brian - avatar
5th Apr 2024, 11:00 AM
Kailash Yandrapu
0
The problem in your code is this " fact = fact * 1; " .. think about that .. if x is 3 for example .. you're gone multiply fact with 1 ..3 time(1*1, 1*1, 1*1) .. to make it work.. you need to multiply fact by x .. " fact *= x " so that you can get .. the right rezult.. if you multiply fact with x you get the next rezult (1*1, 1*2, 1*3) etc..
4th Apr 2024, 7:41 PM
Blud PlayingGames
Blud PlayingGames - avatar