Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Fibonacci and Prime numbers

  Asked By: Thelma    Date: Apr 18    Category: Java    Views: 4331
  

I'm new to Java and trying to write some java code that will accept 2
numbers to start off my Fibonacci list and generate a list of 50 and
print them on screen. I'm also trying to generate some java code that
will generate 500 Prime Numbers.

Anyone got any ideas?

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Gilberto Thompson     Answered On: Apr 18

Read some books a lot of them outthere with the
similar idea.

 
Answer #2    Answered By: Abbas Hashmi     Answered On: Apr 18

0,1,1,2,3,5,8,13...and so on. So, one number is the sum of the two
previous numbers, ie 5+8=13 or 1+2=3.

Something like this might help for a method. I have not tested it:


int temp=0;
int next = 1;
int previous = 0;

for(int i = 0; i < 10; i++)
{
temp = previous + next;
System.out.println(temp);
previous = next;
next = temp;
}


I've seen the Fibonacci sequence written recursively and it looks
something like this:

static int recursiveFib(int n)
{
if ( n < 0 )
return -1;
if ( n == 0)
return 0;
if ( n == 1)
return 1;
return(recursiveFib(n-1) + recursivefib(n-2));
}

I have not tested this either and it will probably trash all of your
memory as is. It needs an escape condition.

There may be a test to find a prime  number in one of the java
packages, I'm not sure. Maybe Math?

I think this works for your prime numbers  but again, test it.

public static void main(String[] args)
{
getPrime();
}


static void getPrime()
{
int counter =0;
int i=0;
while(counter <= 500)
{
if(isPrime(i)==true)
{
System.out.println(i);
counter++;
}//end if
i++;

}//end while
}


static boolean isPrime(int number)
{

if (number % 2==0)
return false;
for (int i = 3; i <= Math.sqrt(number); i += 2)
{
if (number % i ==0)
return false;
}//end for
return true;
}

You might be able to come up with something using a recursive GCD
(greatest common denominator) method.

 
Didn't find what you were looking for? Find more on Fibonacci and Prime numbers Or get search suggestion and latest updates.




Tagged: