Project Euler #28: Number spiral diagonals

Sort by

recency

|

41 Discussions

|

  • + 0 comments
    def calculate_result(n):
        # Calculate the result using the given formula
        w = n - 1
        result = 1 + 4 * ((n * (2 * n + 1) * (2 * n - 1)) // 3 - 1) - 12 * ((w * (w + 1)) // 2)
        return result % (10**9 + 7)
    
    def main():
        t = int(input(""))
    
        for _ in range(t):
            n = int(input()) // 2 + 1
            result = calculate_result(n)
            print(result)
    
    if __name__ == "__main__":
        main()
    
  • + 0 comments

    For C++, we need to use n % mod and inverse modulo to do the division.

    C++

    int mod = 1000000007, imod3 = 333333336;
    int main() {
        long long t, n;
        cin >> t;
        while (t--) {
            cin >> n;
            long long nm = n % mod, n2m = n / 2 % mod;
            long long res = nm * (nm + 1) % mod * (2 * nm + 1) % mod * imod3 - 1;
            cout << (res - 2 * n2m * n2m % mod) % mod << endl;
        }
        return 0;
    }
    
  • + 0 comments

    code in python3

    def res():

    t = int(input())
    for i in range(t):
        n = int(input())//2+1
        w = n-1
        result = 1+4*((n*(2*n+1)*(2*n-1))//3 -1 )-12*((w*(w+1))//2)
        print(result%(10**9+7))
    

    res()

  • + 0 comments

    100/- points python3.
    easy solve

    def sum_calc(n):
        if n==1:
            return 1
        sum=1
    #1,3,5,7,9,13,17,21,25,31
    #for i in range(3,n+1,2):
        #sum+=(i**2)*4-6*(i-1)
    # it would be slower to do the above so I just compute it mathematically as a formula by the help of sum of first n squares
        x=(n-1)//2
        sum+=(n*(n+1)*(2*n+1)//6-1-4*(x*(x+1)*(2*x+1)//6))*4-6*(x)*(x+1)
        return sum
    for _ in range(int(input())):
        n=int(input())
        print(sum_calc(n)%(10**9+7))
    
  • + 0 comments
    def sum_of_spiral_diagonal(n):
        s = (16*(n**3)+30*(n**2)+26*n+ 3)//3
        return s % (10**9+7)
    
    # Read the number of test cases
    t = int(input())
    
    # Iterate over the test cases
    for i in range(t):
        # Read the input and divide it by 2
        n = int(input()) // 2 # this indicates the spiral number
        print(sum_of_spiral_diagonal(n))