Euler problem ask for the sum of all diagonal numbers like red ones above. The prime feature could not be used because not all diagonal positions are prime number. The hint is just every turn in this spiral, the length goes like: 1, 1, 2, 2, 3, 3, 4, 4,...
Since every turn is also the diagonal, except the first one, 2, use this length growth to build the sum is easy:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def approach1(size): | |
diagonal = 0 | |
current = 1 | |
for i in range(1, size+1): | |
current += i | |
diagonal += current | |
# decrease the sum if it is the first odd turn | |
if i%2 != 0: | |
diagonal -= 1 | |
current += i | |
diagonal += current | |
# remove the last turn | |
diagonal -= current | |
print diagonal |
No comments:
Post a Comment