How to print the Fibonacci series and prime number list
These are actually two very basic and simple questions. However, somehow often reminds me of these two problems, sometimes cake does not think of the solution and will be sweating ...................
Let's get down to the truth and paste the code for these two questions.
(1) print the Fibonacci series
// Java program for Fibonacci number using Loop. public static int fibonacciLoop(int number){ if(number == 1 || number == 2){ return 1; } int fibo1=1, fibo2=1, fibonacci=1; for(int i= 3; i<= number; i++){ fibonacci = fibo1 + fibo2; //Fibonacci number is sum of previous two Fibonacci number fibo1 = fibo2; fibo2 = fibonacci; } return fibonacci; //Fibonacci number }
(2) print prime numbers
public static void prime( int number) { for (int i=2; i<number; i++) for (int j=2; j*j<=i; j++) { if (i % j == 0) break; else if (j+1 > sqrt(i)) { System.out.println(i); } } return 0;}
C-language Fibonacci Series
Int I, m, s, k;
FILE * fp;
M = s = 1;
If (fp = fopen (str, "wb + "))
{Fwrite (& m, sizeof (int), 1, fp); fwrite (& s, sizeof (int), 1, fp );
For (I = 2; I <n; I ++) {k = m + s; fwrite (& k, sizeof (int), 1, fp); m = s; s = k ;}
Fclose (fp );
}
Fibonacci Series
The Fibonacci series was introduced by the mathematician Leonardo Fibonacci using rabbit breeding as an example. It is also known as the "Rabbit series ". Generally, a rabbit has the ability to breed after being born two months. A rabbit can have a rabbit every month. If all rabbits do not die, how many rabbits can breed in a year? Let's take a new couple of rabbits for analysis: the first month of the rabbit was not capable of reproduction, so it was still a pair; two months later, there were two pairs of rabbits; three months later, the old rabbit gave birth to another pair, because the rabbit has no reproductive capacity, so there are three pairs; ------ and so on, the following table can be listed: number of months: --- 1---2---3---4---5---6---7---8---9---10---11---12 rabbit logarithm: --- 1---1---2---3---5---8--13--21--34--55--89--144 the numbers 1, 3, 3, 5, 8 --- in the table constitute a series. This series has very obvious characteristics. That is: the sum of the two adjacent items above, which constitutes the next item. This feature proves that the number of rabbits in each month is the number of rabbits in the previous month, and the number of rabbits in the previous month is the number of rabbits in the previous month.