Reputation: 21
I am trying to submit my code to the 'Small factorials' problem on SPOJ. It runs successfully on my IDE but shows run time error (NZEC) on SPOJ. Please suggest a solutions.
import java.util.Scanner;
class Factoria
{
public static void main (String[] args) throws java.lang.Exception
{
int t, n;
int multi = 1;
Scanner tc = new Scanner(System.in);
t = tc.nextInt();
for(int i=0;i<t;i++){
Scanner nc = new Scanner(System.in);
n = nc.nextInt();
for(int f=1;f<=n;f++){
multi = multi * f;
}
System.out.println(multi);
multi = 1;
}
}
}
Upvotes: 2
Views: 595
Reputation: 20344
Your runtime error is likely because you try to initiate a new Scanner
on System.in
when you already have one open. This seems to fail on Java 8 although seems to run OK on Java 7 - both tested on ideone. There is no need to initiate a new Scanner
.
If you simply remove the line
Scanner nc = new Scanner(System.in);
and use tc.nextInt();
instead of nc.nextInt();
it should work.
I note you're doing this for an online competition. You should also note that your factorial will fail (overflow) if the input is > 12 as you're using int
type. I don't know whether this will apply in your case.
import java.util.Scanner;
class Factoria
{
public static void main (String[] args) throws java.lang.Exception
{
int t, n;
int multi = 1;
Scanner tc = new Scanner(System.in);
t = tc.nextInt();
for(int i=0;i<t;i++){
n = tc.nextInt();
for(int f=1;f<=n;f++){
multi = multi * f;
}
System.out.println(multi);
multi = 1;
}
}
}
5
4
3
5
2
1
24
6
120
2
1
Upvotes: 4