Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...Write a MATLAB code to find the sum of all even-numbered terms in the sequence whose values are less than or equal to 500. (Hint: You may find the built-in commands "fibonacci" and "mod" useful for this problem.)

Respuesta :

Answer:

  1. sum = 0;
  2. n =  1;
  3. f = fibonacci(n);
  4. while f <= 500
  5.    if(mod(f,2)==0)
  6.        sum = sum + f;
  7.    end
  8.    n = n + 1;
  9.    f = fibonacci(n);    
  10. end
  11. disp(sum)

Explanation:

Firstly, let's define several variables which are necessary to hold the value of total of Fibonacci sequence, sum, Fibonacci index, n and Fibonacci term, f (Line 1 - 3). We can get the first Fibonacci term using the Matlab built-in function fibonacci() (Line 3).

Since the Fibonacci term should be less than or equal to 500, create a while condition that meet the requirement (Line 5). Within the while loop, check if the current Fibonacci term is an even number. This can be achieved by using mod() function to calculate the f modulus by 2 (Line 6). If the result is zero, the f is an even number and f value will be added with variable sum.

Next increment the Fibonacci index by 1 and use the same function fibonacci() to get the next Fibonacci term, f,  and repeat the same process as described above until the f  becomes bigger than 500.

At the end, display the result (Line 13). The result shall be 188.

ACCESS MORE