Lines 51
Euler28 (8)
##### Permissions
Owner: jsimones
Group Owner: SnortSnort
Viewable by Everyone
Editable by All Siafoo Users

# Project Euler 28 0

 Language Python
# 's
` 1""" 2Number spiral diagonals 3Problem 28 4Starting with the number 1 and moving to the right in a clockwise direction a 5 5by 5 spiral is formed as follows: 6 721 22 23 24 25 820  7  8  9 10 919  6  1  2 111018  5  4  3 121117 16 15 14 131213It can be verified that the sum of the numbers on the diagonals is 101.1415What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed16in the same way?1718"""19import numpy as np2021def spiral_diagonal_sum1(N):22    """23    Step through each corner number in the NxN spiral pattern, using the fact24    that the side length of each concentric box grows by 2.2526    """27    term, diagonal_sum = 1, 128    step, i = 2, 1  # dist b/w adjacent corners and the corner index (1 - 4)29    while step <= N - 1:30        term += step31        diagonal_sum += term32        i += 133        if i > 4:34            step += 235            i = 136    return diagonal_sum3738def spiral_diagonal_sum2(N):39    """40    In a box of side length n, the number in the upper-right corner is n^2 and41    the other corners are n^2 minus 1-, 2-, and 3-times n-1 (thanks, Mike!).42    This is way faster than spiral_diagonal_sum1.4344    """45    diagonal_sum = 146    for n in range(3, N + 1, 2):47        diagonal_sum += 4 * n**2 - 6 * n + 648    return diagonal_sum4950def spiral_diagonal_sum3(N):51    """52    Numpy version of spiral_diagonal_sum2. Faster than spiral_diagonal_sum2.5354    """55    n = np.arange(3, N + 1, 2)56    box_sum = 4 * n**2 - 6 * n + 657    return np.sum(box_sum) + 15859def main():60    print spiral_diagonal_sum3(1001)6162if __name__ == '__main__':63    main()`