Сумма чисел Фибоначчи из иходного массива

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

High-performance Fibonacci numbers implementation in PHP

rafaelbernard/php-fibonacci

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, . 

Often, especially in modern usage, the sequence is extended by one more initial term:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, . 

This implementation has two methods: fibonacci and fibonacci_big .

The fibonacci function is more efficient, however, it returns correct numbers between 0 and 93 (inclusive). The fibonacci_big function, on the other hand, is less efficient but returns practically any Fibonacci number.

$f = fibonacci(10); $fb = fibonacci_big(200);
Tests - Success. Tests - Success. Tests - Success. Benchmark 10 run: 167,864/sec or 0.0059572034504122ms/op Benchmark 20 run: 1,370/sec or 0.72992700729927ms/op Benchmark 10 tuned run: 3,459,629/sec or 0.00028904833437343ms/op Benchmark 20 tuned run: 2,151,116/sec or 0.00046487497652381ms/op 
100: 3.5422484817926E+20 200: 2.8057117299251E+41 300: 2.2223224462942E+62 400: 1.7602368064501E+83 

About

High-performance Fibonacci numbers implementation in PHP

Источник

Fibonacci Series PHP

Fibonacci Series PHP

If said in layman language, a Fibonacci Series is a series of elements formed or obtained, when the previous two elements are added to form the next element until we get the required series size. We usually start the Fibonacci Series with 0 and 1.

Web development, programming languages, Software testing & others

The series once formed, appears as below:

As stated above, the next number is obtained by adding up the previous two numbers.

  • The ‘2’ on the 4 th position (n th position) in the above-given series, is obtained by adding its preceding two numbers[ [n-1] and n-2]), 1.
  • The ‘3’ is obtained by adding its preceding two numbers,2.
  • The ‘5’ is obtained by adding its preceding two numbers,3.
  • And so on.
Читайте также:  Css img src height width

Fibonacci Series in PHP and the Logic

Here we will see specifically obtaining the Fibonacci Series while we are working in a PHP environment. The difference is the format in which we will be coding, i.e. using a starting tag for a PHP script and its ending tag.

This will help you to understand and learn how this Fibonacci series is generated in PHP using two methods which is the Iterative way and the Recursive way.

When we are given a number i.e ‘n’ which is the series size, we will try to find the Fibonacci Series up to the given number.

For example, if we are required to create Fibonacci for n=5, we will display elements till the 5th term.

Logic in PHP

Logic is the same as stated above. Here we have given n=10, i.e. we need to find the elements till nth term. Thus we will keep on following our logic till we have n terms in our series.

Let us see one of the examples given above.

In one of the above example we have n=9 and Logic says that:

  • Initialize the first number as 0.
  • Initialize the second number as 1.
  • Print the first and second numbers.
  • The loop starts here.
  • For next element in the series i.e. 3 rd element [n th element],we will be adding its immediate preceding two numbers [(n-1) and (n-2)] to get the next number in the series, like here, 0 + 1 = 1.
  • n – 1 = 3 – 1 = 2nd element of the series = 1
  • n – 2 = 3 – 2 = 1st element of the series = 0 3 rd element = (n-1) + (n-2) = 1 + 0 = 1

Thus, the third element in the series is 1.

  • Similarly according to the logic, to get the 4 th element [n] of the series we need to add its preceding numbers e. (n-1) and (n-2) element.

Now at this point, ‘n’ is equal to ‘4’:

  • n – 1 = 4 – 1 = 3rd element of the series = 1
  • n – 2 = 4 – 2 = 2nd element of the series = 1 4 th element = (n-1) + (n-2) = 1 + 1 = 2

Thus, we get our 4 th element as 2.

Thus, for ‘n’ equals to 9, following the same logic as explained above we get sequence as, Fibonacci sequence is 0 1 1 2 3 5 8 13 21

PHP Series for Fibonacci Printing with Two Approaches

There are basically two famous versions on how we can write a program in PHP to print Fibonacci Series:

As usual in PHP, we will be using the ‘echo’ statement to print the output.

1. The Non-Recursion Way

Also known as for using the Iteration. This is the approach where we will start the series with 0 and 1. After which we will print the first and second numbers. Following which we will start with our iteration using a loop, here we are using a while loop.

PHP script for printing first 10 Fibonacci Series elements.

 > //for a pre defined number for Fibonacci. $n=10; Fibonacci($n); ?>

Code Explanation:

  1. Here n is defined as equal to 10, so the logic will run till nth element e. Until we have n=10 elements in the series.
  2. First element is initialized to 0 and second element is initialized to 1, e. num1 = 0 and num2 = 1.
  3. The two elements i.e. num1 and num2 are printed as the first and second elements of the Fibonacci series.
  4. The logic we discussed will be used from here on and our iteration loop starts.
  5. According to our logic, to get num3, we need to add num1 and num2. Since currently num1 = 0 and num2 = 1, num3 comes out as 1.
  6. Now new number obtained is placed in num2 variable and num2 is saved in num1 variable. Basically simple swapping is taking place so that, now num1 is equal to ‘1’ and num2 = newly obtained num3 i.e. ‘1’.
  7. So when the next iteration happens and num3 is obtained by adding current values of num1 and num2, which, according to our PHP script, are as follows:
      • num1 = 1
      • num2 = 1
      • num3 = num1 + num2 = 1 + 1 = 2

      Thus we get our next number in the Fibonacci Series.

      1. Similarly, the iteration keeps on till we achieve n = 10, size of the series that was defined in the program itself.

      When the above program is executed, we get the output as follows:

      fibonacci series 1

      2. The Recursion Way

      By recursion, we mean the way where the same function is called repeatedly until a base condition is achieved or matched. At this point, recursion is stopped.

      The said “function is called repeatedly” phrase points to the section in your code where we will define our logic for the Fibonacci Series.

      Below is an example of generating Fibonacci Series in PHP, using If-Else conditions giving way for our recursive approach.

      Here is the PHP Scripts for printing the first 15 elements for Fibonacci Series.

       //For a given n=15 $num =15; for($counter = 0; $counter < $num; $counter++) < echo Fibonacci($counter).' '; >?>

      Code Explanation:

      This is the recursive way, which means our function that contains our logic is called again and again for generating the next element in the series until our condition for achieving a specific series size is obtained.

      In Iterative approaches, the First and Second element is first initialized and printed. Here we allow a For Loop to give us our first and second elements starting with 0 and 1.

      1. We are using a For loop having a ‘counter’ variable that starts with 0. The For loop works up till the given ‘n’, size for the series.
      2. when loop starts, with the counter variable as 0, we use the recursion approach and call our defined function, Fibonacci ( ).
      3. Here code starts, with If and Else IF condition.
      4. First IF condition checks if ‘num’ variable holds value as ‘0’, if yes, then the code prints or returns ‘0’ as the element for the series.
      5. Similarly, second Else-If condition checks for the value ‘1’, if the ‘num’ variable holds ‘1’ as its value, the program returns it as it is.
      6. Next Else condition recursively calls the Fibonacci function for’ num’ values other than ‘0’ and ‘1’, continuing to reading the values from the For loop counter.

      This is where our Fibonacci Logic comes into work and the next number in the sequence is obtained by adding its previous two numbers. Because this is the recursive method, we need to give a counter value to count the recursions equal to nth value, which is being handled by our For Loop.

      When the above program or code is executed, the following output is displayed.

      fibonacci series 2

      The Fibonacci Series does not only appear in mathematics or science calculations but in nature too, have you ever noticed Yellow chamomile flower head.

      The Fibonacci Series if plotted on a graph, it forms a spiral called Fibonacci Spiral. It is also one of the gems given by Indian soil. It is found in Indian Mathematics as early as 200 BC in the works done by the mathematician, Pingala. Later Fibonacci introduced the sequence to European countries in his book Liber Abacci in 1200s.

      This has been a guide to Fibonacci Series PHP. Here we discuss the introduction and PHP Lines for Printing Fibonacci Series with Two Approaches. You may also have a look at the following articles to learn more –

      25+ Hours of HD Videos
      5 Courses
      6 Mock Tests & Quizzes
      Verifiable Certificate of Completion
      Lifetime Access
      4.5

      92+ Hours of HD Videos
      22 Courses
      2 Mock Tests & Quizzes
      Verifiable Certificate of Completion
      Lifetime Access
      4.5

      83+ Hours of HD Videos
      16 Courses
      1 Mock Tests & Quizzes
      Verifiable Certificate of Completion
      Lifetime Access
      4.5

      PHP Course Bundle — 8 Courses in 1 | 3 Mock Tests
      43+ Hours of HD Videos
      8 Courses
      3 Mock Tests & Quizzes
      Verifiable Certificate of Completion
      Lifetime Access
      4.5

      Источник

      Нормально ли сделал тестовое задание на PHP (числа Фибоначчи)?

      Работал почти всегда на себе, нет опыта в тестовых заданиях. Вот работодатель скинул три задания, сделал одно для интереса, попинайте.. как в общем с оформлением/алгоритмом, в таком ключе нормально будет?

      Скажу сразу, алогоритм сам написал, да есть в сети тыщи вариантом, в том числе через рекурсию, но уж очень наворочено как-то.. да красиво, но не совсем понятно )

      Короче вот задание (я его изменил немного):

      Дан массив [3279, 920, 4181, 8, 1, 4360, 407, 9950, 2098, 8579, 4914, 7204, 8875]. В нем нужно найти числа Фибоначчи ( 1, 1, 2, 3, 5, 8, 13, 21. ), затем вычислить сумму.

       return $fibonacciNumbers; > // Исходный массив $inputNumbers = [3279, 920, 4181, 8, 337, 13, 918, 4923, 1, 4448, 8, 4756, 4012, 7467, 89, 21, 9238, 2326, 6453, 89, 4606, 3413, 3, 9950, 2098, 8579, 4914, 7204, 8875 ]; // Инициализируем массив с первыми тремя числами Фибоначчи $fibonacciNumbers = array(0, 1, 1); // Формируем канонический ряд Фибоначчи от нуля до максимального значения, // находящегося в исходном массиве sort($inputNumbers); $lastFibonacciNumber = $inputNumbers[count($inputNumbers) - 1]; for ($i = 0; $i // Находим смежные значения в исходном массиве и массиве с числами Фибоначчи, // обнуляя индексы $resultFibonacci = array_values(array_intersect($fibonacciNumbers, $inputNumbers)); ?>      Числа Фибоначчи из иходного массива:   ?> 
      Сумма чисел Фибоначчи из иходного массива:

      Источник

Оцените статью