I'm writing a program that calculates the nth position of the Fibonacci Sequence. The minimum end goal of the program is to be able to print the 100th, the ideal end goal is to calculate beyond that point. For this reason I have to use primitive type long to deal with how large the numbers are.
public static long fibonacci (long n)
{
double phi = ((1 + Math.sqrt(5))/2);
double result;
result = ((Math.pow(phi, n))/Math.sqrt(5));
return (long) result;
}
This takes a number called Phi, to the power of the position I want to find. Then that value is divided by the square root of 5. Now the 100th Fibonacci Number is 354224848179262000000 I can successfully get this number but due to doubles not being able to handle large numbers it's compressed into Scientific Notation. (Or at least I assume that's why it's in Scientific Notation)
So my thought process is, by casting it to a long, a variable type that can manage larger numbers it would print it as the whole, "354224848179262000000", not "3.542248481792631E20." So I successfully casted to a long and return the result and this is where the problem comes in. (Sorry for having so much background information to go through)
When I cast the decimal, which is the correct answer, it converts the number into something completely different. The number I get is 9223372036854775807. So can someone explain what I did wrong, or what I need to do to get, "3.542248481792631E20" to print out as, "354224848179262000000" Thanks everyone!
Here is the entirety of my code, hopefully you guys can spot something or explain something to me. Maybe I am misunderstanding how longs function.
import java.util.Scanner;
public class FibLong
{
public static void main(String[] args)
{
long position;
long answer;
Scanner input = new Scanner (System.in);
System.out.print ("Please enter an Nth position within the Fibonacci sequence: ");
position = input.nextLong();
answer = fibonacci(position);
System.out.printf ("The Fibonacci number of position " + position + " is the number " + answer);
}
public static long fibonacci (long n)
{
double phi = ((1 + Math.sqrt(5))/2);
double result;
result = ((Math.pow(phi, n))/Math.sqrt(5));
return (long) result;
}
}