Recursive Digit Sum

Sort by

recency

|

606 Discussions

|

  • + 0 comments

    You can solve this mathematically in Python with:

    result = (int(n) * int(k)) % 9
    return result if result != 0 else 9
    

    However, if n is a very long number, int(n) may raise a ValueError due to the digit limit introduced in recent Python versions. You can bypass this by increasing the limit:

    import sys
    sys.set_int_max_str_digits(100000)
    

    Use with caution, especially when handling untrusted input, as increasing the limit can expose your code to denial-of-service risks.

    Reference: Python Docs – Integer string conversion length limitation

  • + 0 comments

    If you're having trouble with timeouts or the last 3 cases:

    1. Don't try to build a string of len(n) * k length or try to implement a loop over the string repeatedly - just calculate the sum of the digits of n then multiply by k
    2. If you fail cases 5, 7, 8 after that, make sure your integer type is at least 64 bits as the values for those cases overflow 32 bit integers (even though the setup for languages like golang always want 32 bit answers)
  • + 0 comments

    in java int isn't big enough have to use a bigger data type for the sum

  • + 0 comments
    def superDigit(n, k):
        sum1=sum(int(i) for i in  n)
        sum2=sum1*k
        while sum2>=10:
            sum2=sum(int(i) for i in str(sum2))
        return sum2
    
  • + 1 comment

    148, 3

    1+4+8 = 13 1+3 = 4 4+0 = 4

    Wrong Result = 4 Correct Result = 3

    Bug