PDA

Click to See Complete Forum and Search --> : [RESOLVED] different answer


vb_student
Jun 21st, 2006, 03:54 PM
Hello

i was tring to figure out what the result of factorial for 21 using the following code.

java code


import java.io.*;
/**
*
* @author
*/
public class mywelcome {
public static void main (String[] args) throws IOException
{
BufferedReader userin = new BufferedReader
(new InputStreamReader(System.in));
String inputData;
long N, fact = 1;

System.out.println( "Enter N:" );
inputData = userin.readLine();
N = Integer.parseInt( inputData );

if ( N >= 0 )
{
while ( N > 1 )
{
fact = fact * N;
N = N - 1;
}
System.out.println( "factorial is " + fact );
}
else
{
System.out.println("N must be zero or greater");
}
}
}


when i use the code in the netbeans environment, i get the answer -4249290049419214848
but the following link states the answer should be 51090942171709440000

http://chortle.ccsu.edu/CS151/Notes/chap17/ch17_12.html?factText=N+must+be+an+integer+zero+or+greater&N=20

can you guys tell me why the difference?

System_Error
Jun 21st, 2006, 07:14 PM
I don't agree with what how you're doing it. Simply use a for loop:


long total = 1;
for (int index=21; index >=1; --index)
{
total *=index;
}


Something along those lines... You can use recursion, but I'd prefer this method.

ComputerJy
Jun 22nd, 2006, 06:14 AM
That's JavaScript, it's totally different than java besides "51090942171709440000" is very big to contain in a "long" variable,
try this:
import java.io.* ;

/**
*
* @author Moyeen
*/
public class My
{
public static void main (String[] args) throws IOException {
BufferedReader userin = new BufferedReader(new InputStreamReader(System.in)) ;
String inputData ;
int N;
double fact = 1 ;

System.out.println("Enter N:") ;
inputData = userin.readLine() ;
N = Integer.parseInt(inputData) ;

if (N >= 0) {
while (N > 1) {
fact = fact * N ;
N-- ;
}
System.out.println("factorial is " + fact) ;
}
else {
System.out.println("N must be zero or greater") ;
}
}
}

vb_student
Jun 23rd, 2006, 01:22 PM
thanks for the replies

i have just started on java, and am going through this tutorial on central conneticut state university's web tutorial on java

ComputerJy
Jun 23rd, 2006, 03:58 PM
Good, welcome to java :D
if you are done, please mark the thread resolved

vb_student
Jun 23rd, 2006, 06:05 PM
done. thanks again

ComputerJy
Jun 23rd, 2006, 07:08 PM
http://noteme.com/vb_extension/smilies/rotf.gif this is not how you mark a thread resolved!
Click on "Thread Tools" and select "Mark Thread Resolved"

CornedBee
Jun 24th, 2006, 04:06 AM
double is potentially inaccurate. Use java.math.BigInteger instead. Note that you have to use the class's member functions instead of normal mathematical operators, though.

vb_student
Jun 24th, 2006, 11:08 AM
done :)