The Pythagorean Theorem

Time limit1sMemory limit128 MB

Summary
Given n, count ordered triples (a,b,c) with 1<=a<=b<=n-1 and c<=n-1 such that a^2+b^2 is congruent to c^2 modulo n.
Level

Hard8 of 10

Topics
Number theory, Math, Brute force, Implementation
Solved
No attempts yet

Problem

Sanggeun loves triangles, and right triangles most of all.

A right triangle has side lengths that are positive integers aa, bb, cc with a≤ba \le b and a2+b2=c2a^2 + b^2 = c^2.

After learning modular arithmetic, Sanggeun decided to apply it to the Pythagorean theorem.

Given an integer nn, he wants to count the ordered triples (a,b,c)(a, b, c) with 1≤a,b,c≤n−11 \le a, b, c \le n-1 and a≤ba \le b that satisfy

a2+b2≡c2(modn).a^2 + b^2 \equiv c^2 \pmod{n}.

Write a program that, given nn, computes the number of such triples (a,b,c)(a, b, c).

Input

The first line contains an integer nn. (2≤n≤500,0002 \le n \le 500{,}000)

Output

Print the number of triples (a,b,c)(a, b, c) that satisfy the condition.

Examples2

  1. Example 1

    Input
    7
    
    Expected output
    18
    
  2. Example 2

    Input
    15
    
    Expected output
    64