TheAlgorithms-Python

Форк
0
58 строк · 1.2 Кб
1
"""
2
Problem 28
3
Url: https://projecteuler.net/problem=28
4
Statement:
5
Starting with the number 1 and moving to the right in a clockwise direction a 5
6
by 5 spiral is formed as follows:
7

8
    21 22 23 24 25
9
    20  7  8  9 10
10
    19  6  1  2 11
11
    18  5  4  3 12
12
    17 16 15 14 13
13

14
It can be verified that the sum of the numbers on the diagonals is 101.
15

16
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed
17
in the same way?
18
"""
19

20
from math import ceil
21

22

23
def solution(n: int = 1001) -> int:
24
    """Returns the sum of the numbers on the diagonals in a n by n spiral
25
    formed in the same way.
26

27
    >>> solution(1001)
28
    669171001
29
    >>> solution(500)
30
    82959497
31
    >>> solution(100)
32
    651897
33
    >>> solution(50)
34
    79697
35
    >>> solution(10)
36
    537
37
    """
38
    total = 1
39

40
    for i in range(1, int(ceil(n / 2.0))):
41
        odd = 2 * i + 1
42
        even = 2 * i
43
        total = total + 4 * odd**2 - 6 * even
44

45
    return total
46

47

48
if __name__ == "__main__":
49
    import sys
50

51
    if len(sys.argv) == 1:
52
        print(solution())
53
    else:
54
        try:
55
            n = int(sys.argv[1])
56
            print(solution(n))
57
        except ValueError:
58
            print("Invalid entry - please enter a number")
59

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.