TheAlgorithms-Python
58 строк · 1.2 Кб
1"""
2Problem 28
3Url: https://projecteuler.net/problem=28
4Statement:
5Starting with the number 1 and moving to the right in a clockwise direction a 5
6by 5 spiral is formed as follows:
7
821 22 23 24 25
920 7 8 9 10
1019 6 1 2 11
1118 5 4 3 12
1217 16 15 14 13
13
14It can be verified that the sum of the numbers on the diagonals is 101.
15
16What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed
17in the same way?
18"""
19
20from math import ceil21
22
23def solution(n: int = 1001) -> int:24"""Returns the sum of the numbers on the diagonals in a n by n spiral25formed in the same way.
26
27>>> solution(1001)
28669171001
29>>> solution(500)
3082959497
31>>> solution(100)
32651897
33>>> solution(50)
3479697
35>>> solution(10)
36537
37"""
38total = 139
40for i in range(1, int(ceil(n / 2.0))):41odd = 2 * i + 142even = 2 * i43total = total + 4 * odd**2 - 6 * even44
45return total46
47
48if __name__ == "__main__":49import sys50
51if len(sys.argv) == 1:52print(solution())53else:54try:55n = int(sys.argv[1])56print(solution(n))57except ValueError:58print("Invalid entry - please enter a number")59