Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Answer to coding puzzle on Narcissistic Numbers
REPORT znarcissistic_numbers.
" https://blogs.sap.com/2021/03/20/another-abap-puzzle-narcissistic-numbers/
PARAMETERS p_digits TYPE i DEFAULT 5.
CLASS lcl_narcissist DEFINITION CREATE PUBLIC.
PUBLIC SECTION.
METHODS run IMPORTING i_length TYPE i.
PRIVATE SECTION.
DATA power TYPE i VALUE 1.
METHODS check IMPORTING i_number TYPE i
i_sum_of_powers TYPE i
i_pos TYPE i.
ENDCLASS.
CLASS lcl_narcissist IMPLEMENTATION.
METHOD run.
check( i_number = 0
i_sum_of_powers = 0
i_pos = i_length ).
ENDMETHOD.
METHOD check.
CHECK i_sum_of_powers <= i_number. "Performance
DO 10 TIMES.
DATA(digit) = sy-index - 1.
IF i_pos > 1.
check( i_number = i_number + digit * 10 ** ( i_pos - 1 )
i_sum_of_powers = i_sum_of_powers + digit ** power
i_pos = i_pos - 1 ).
IF power < i_pos.
power = i_pos.
ENDIF.
ELSE.
IF i_number + digit = i_sum_of_powers + digit ** power.
WRITE |{ i_number + digit } |.
ENDIF.
ENDIF.
ENDDO.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
NEW lcl_narcissist( )->run( p_digits ).
@pokrakam

This comment has been minimized.

Copy link
Owner Author

@pokrakam pokrakam commented Apr 5, 2021

Deliberate strategy to use recursion and (mostly) immutable data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment