for loop - Factorial Java Program -


i want factorial program in java using loop. example want take user input, lets 10, , multiply 10*9*8*7*6*5*4*3*2*1. need constructing for loop. code below have far i'm not sure go after.

import java.util.scanner; import java.lang.math; public class factorial {      public static void main(string[] args) {         int num;         scanner input = new scanner(system.in);         system.out.println("enter number: ");         num = input.nextint();     } } 

try

public static void main(string[] args) {     int num;     int fact=1;     scanner input = new scanner(system.in);     system.out.println("enter number: ");     num = input.nextint();     (int i=2;i<=num; i++){         fact=fact*i;     }      system.out.println("factorial: "+fact); } 

as @marko topolnik mentioned in comments code work inputs 12. larger inputs output infinity due overflow.

for numbers larger 12 should use higher data type biginteger

you can try:

public static void main(string[] args) {     biginteger num;     biginteger fact = biginteger.valueof(1);     scanner input = new scanner(system.in);     system.out.println("enter number: ");     num = input.nextbiginteger();     (int = 2; <= num; i++){         fact = fact.multiply(biginteger.valueof(i));     }     system.out.println(fact); } 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -