ABAP arithmetic problem: Fibonacci (Fibonacci) series

Fibonacci (Fibonacci) series is a classic recursive relations define the number of columns.

The first term is 0, the second term is 1, after each of which is the sum of the foregoing two.

(Sap labs interview questions, asked to write on the whiteboard abap algorithm in a different way ... There is no psychological preparation, write a recursive first pass, possibly complexity is not very good, so I write a interviewer, so I wrote the following code)

PARAMETERS: p_number   TYPE i OBLIGATORY.

DATA : x TYPE i VALUE 0,
       y TYPE i VALUE 1.

" 算法1
CASE p_number.
  WHEN 0. WRITE '序号无效'.
  WHEN 1. WRITE x.
  WHEN 2. WRITE y.
  WHEN OTHERS.
    DO p_number - 2 TIMES.
      y = x + y.
      x = Y - x.
    ENDDO .
    WRITE and.
ENDCASE .

Stop using the replacement values ​​xy cycle looks a lot better results, the code is also more compact and easy to understand.

Incidentally Tip Note boundary conditions, such as when a user input, 2, of course, not necessary to calculate this time.

So far is linear time complexity, and on this classic series, there are many more kinds of algorithms, we can further study.

 

Guess you like

Origin www.cnblogs.com/yibing-jia/p/11278027.html