beecrowd | 3187

Just a Few More Triangles!

By Per Austrin FI Finland

Timelimit: 1

Simon Haples is a somewhat peculiar person. Not quite hip, not quite square, he is more of a triangular nature: ever since childhood, he has had an almost unhealthy obsession with triangles. Because of his discrete nature, Simon’s favorite kind of triangles are the Pythagorean ones, in which the side lengths are three positive integers A, B, and C such that A ≤ B and A² +  = .

Recently, Simon has discovered the fantastic world of counting modulo some integer N. As you may imagine, he quickly realizes that there are multitudes of Pythagorean triples to which he has previously been oblivious! Simon therefore sets out to find all Pythagorean triples modulo N, i.e., all triples of integers A, B and C between 1 and N − 1 such that A ≤ B and  +  ≡  (mod N).

As Simon’s best friend, you realize that there is not much hope in deterring Simon from his crazy plans, so you decide to help him by computing how many such triples there are, so that Simon will know when his work is done.


The input consists of a single integer N, satisfying 2 ≤ N ≤ 500 000.


Output the number of Pythagorean triples modulo N.

Input Samples Output Samples