Skip to content

Instantly share code, notes, and snippets.

@boghyon
Last active September 21, 2018 10:54
Show Gist options
  • Save boghyon/bf39de3681012fc4df2d7fbf1fc3b910 to your computer and use it in GitHub Desktop.
Save boghyon/bf39de3681012fc4df2d7fbf1fc3b910 to your computer and use it in GitHub Desktop.
N-th Fibonacci number in ABAP using a recursive Function Module (not memoized yet!!)
FUNCTION z_nth_fibo_number.
*"----------------------------------------------------------------------
*"*"Local Interface:
*" IMPORTING
*" VALUE(IV_INDEX) TYPE I
*" EXPORTING
*" VALUE(EV_FIBO_NUMBER) TYPE I
*" EXCEPTIONS
*" INDEX_LOWER_THAN_ZERO
*"----------------------------------------------------------------------
* Returns a Fibonacci number on n-th index.
* Given 1, 1, 2, 3, 5, 8, 13, 21, ...
* The result is 5 if n = 5.
* The result is 21 if n = 8.
*----------------------------------------------------------------------
* Author: Boghyon Hoffmann
* TODO: Memoize this function to avoid repeating same calculations for which the results have been already submitted before.
*----------------------------------------------------------------------.
IF iv_index < 0. "exception handling
RAISE index_lower_than_zero.
ELSE. "calculate the result
DATA(index_substracted1) = iv_index - 1.
DATA(index_substracted2) = iv_index - 2.
IF iv_index LE 2.
ev_fibo_number = 1.
ELSE.
DATA(result1) = 0.
CALL FUNCTION 'Z_NTH_FIBO_NUMBER'
EXPORTING
iv_index = index_substracted1
IMPORTING
ev_fibo_number = result1.
DATA(result2) = 0.
CALL FUNCTION 'Z_NTH_FIBO_NUMBER'
EXPORTING
iv_index = index_substracted2
IMPORTING
ev_fibo_number = result2.
ev_fibo_number = result1 + result2. "return
ENDIF.
ENDIF.
ENDFUNCTION.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment