나는 이렇게 학습한다/Algorithm & SQL

0128. Gauß needs help! (Sums of a lot of numbers).

daco2020 2023. 1. 28. 17:38

Due to another of his misbehaved, the primary school's teacher of the young Gauß, Herr J.G. Büttner, to keep the bored and unruly young schoolboy Karl Friedrich Gauss busy for a good long time, while he teaching arithmetic to his mates, assigned him the problem of adding up all the whole numbers from 1 through a given number n.

Your task is to help the young Carl Friedrich to solve this problem as quickly as you can; so, he can astonish his teacher and rescue his recreation interval.

Here's, an example:

f(n=100) // returns 5050 

It's your duty to verify that n is a valid positive integer number. If not, please, return false (None for Python, null for C#, 0 for COBOL).



Solution:

def validate_int(func):
    def wrapper(n):
        if not isinstance(n, int):
            return
        if n < 1:
            return 
        return func(n)
    return wrapper


@validate_int
def f(n: int) -> int:
    return sum(range(1, n+1))