Update recursive_digit_sum.py

This commit is contained in:
mankala sharathchandra 2024-10-18 23:13:55 +05:30 committed by GitHub
parent 4cde2d498b
commit 849e0b38d5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,7 +1,7 @@
""" """
The super digit problem is defined as follows: The super digit problem is defined as follows:
Given an integer represented as a string and an integer k, Given an integer n represented as a string and an integer k,
the goal is to find the super digit of the number formed by concatenating the goal is to find the super digit of the number formed by concatenating
the integer n k times. the integer n k times.
The super digit of a number is defined recursively: The super digit of a number is defined recursively:
@ -14,46 +14,44 @@ super_digit(9875987598759875), which can be reduced by summing its digits.
from __future__ import annotations from __future__ import annotations
def super_digit(n_str: str, repetitions: int) -> int:
def superDigit(n: str, k: int) -> int:
""" """
Computes the super digit of a number formed by concatenating n k times. Computes the super digit of a number formed by concatenating n_str repetitions times.
Parameters: Parameters:
n (str): The string representation of the integer. n_str (str): The string representation of the integer.
k (int): The number of times to concatenate n. repetitions (int): The number of times to concatenate n_str.
Returns: Returns:
int: The super digit of the concatenated number. int: The super digit of the concatenated number.
>>> superDigit("148", 3) >>> super_digit("148", 3)
3 3
>>> superDigit("9875", 4) >>> super_digit("9875", 4)
8 8
>>> superDigit("123", 3) >>> super_digit("123", 3)
9 9
""" """
# Calculate the initial sum of the digits in n # Calculate the initial sum of the digits in n_str
digit_sum = sum(int(digit) for digit in n) digit_sum = sum(int(digit) for digit in n_str)
# Multiply the sum by k # Multiply the sum by repetitions
total_sum = digit_sum * k total_sum = digit_sum * repetitions
# Recursive function to find the super digit # Recursive function to find the super digit
while total_sum >= 10: while total_sum >= 10:
total_sum = sum(int(digit) for digit in str(total_sum)) total_sum = sum(int(digit) for digit in str(total_sum))
return total_sum return total_sum
if __name__ == '__main__':
if __name__ == "__main__": # Read input and split it into n_str and repetitions
# Read input and split it into n and k
first_multiple_input = input().rstrip().split() first_multiple_input = input().rstrip().split()
n = first_multiple_input[0] # n as a string n_str = first_multiple_input[0] # n as a string
k = int(first_multiple_input[1]) # k as an integer repetitions = int(first_multiple_input[1]) # repetitions as an integer
# Call the superDigit function and print the result # Call the super_digit function and print the result
result = superDigit(n, k) result = super_digit(n_str, repetitions)
print(result) print(result)