Program to Find Out the Number of Squares in a Grid in Python

PythonServer Side ProgrammingProgramming

Suppose we have two values p and q, we have to find the number of unique squares that can be generated from a grid with p rows and q columns in which the points are placed evenly. If the answer is very large return result mod 10^9 + 7. In this problem, a square is a set of 4 points that form the four vertices of a square. The sides of the square must have the same length, and it does not always have the need to be aligned with the axes of the grid.

So, if the input is like p = 4, q = 4, then the output will be 20.

To solve this, we will follow these steps −

  • for i in range minimum of r to c, do,

    • ans := ans +(r - i) *(c - i) * i

    • return ans mod (10^9 + 7)

Example 

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def solve(self, r, c):
      ans = 0
      for i in range(min(r, c)):
         ans += (r - i) * (c - i) * i
      return ans % (10 ** 9 + 7)
ob = Solution()
print(ob.solve(4,4))

Input

p = 4
q = 4

Output

20
raja
Published on 23-Dec-2020 06:47:48
Advertisements