Computing persistence number of an integer

后端 未结 3 1054
难免孤独
难免孤独 2021-01-26 13:45

I am trying to make a code that does the following:

Multiplying the digits of an integer and continuing the process gives the surprising result that the

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-26 14:00

    Functions are friends.

    Consider a function, getEnds(x), which when passed an integer, x will extract the first digit and the last digit (as integers) and return the result as a tuple in the form (first_digit, last_digit). If x is a single-digit number the tuple will contain one element and be in the form (x), otherwise it will be two. (A simple way to do this is to turn the number into a string, extract the first/last digit as a string, and then convert said strings back into numbers... however, there are many ways: just make sure to honor the function contract, as stated above and -- hopefully -- in the function documentation.)

    Then, where n is the current number we are finding the persistence for:

    ends = getEnds(n)
    while ends contains two elements
       n = first element of ends times second element of ends
       ends = getEnds(n)
    # while terminates when ends contained only one element
    # now it's only a matter of "counting" the persistence
    

    For added points, make sure this is in a -- [an] appropriately named/documented -- function as well and consider the use of a recursive function instead of a while-loop.

    Happy coding.

提交回复
热议问题