Maximum of sum and product of digits until number is reduced to a single digit | Function to sum the digits until it becomes a single digit ; Function to product the digits until it becomes a single digit ; Loop to do sum while sum is not less than or equal to 9 ; Function to find the maximum among repeated sum and repeated product ; Driver code
def repeatedSum ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 9 if ( n % 9 == 0 ) else ( n % 9 ) NEW_LINE DEDENT def repeatedProduct ( n ) : NEW_LINE INDENT prod = 1 NEW_LINE while ( n > 0 or prod > 9 ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT n = prod NEW_LINE prod = 1 NEW_LINE DEDENT prod *= n % 10 NEW_LINE n //= 10 NEW_LINE DEDENT return prod NEW_LINE DEDENT def maxSumProduct ( N ) : NEW_LINE INDENT if ( N < 10 ) : NEW_LINE INDENT return N NEW_LINE DEDENT return max ( repeatedSum ( N ) , repeatedProduct ( N ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 631 NEW_LINE print ( maxSumProduct ( n ) ) NEW_LINE DEDENT