GESP Level 3 C++ Programming (50C++): How to Determine Perfect Squares?

For the GESP Level 3 Exam:[GESP202403 Level 3] Perfect SquaresThis problem is somewhat challenging. Generally, one would use a function to calculate the square root, and after taking the square root, check if it is an integer. However, this approach can lead to many detours, such as converting at the decimal point, multiplying by 10, and checking if modulo 10 equals 0, all of which can cause precision loss.Problem statement:GESP Level 3 C++ Programming (50C++): How to Determine Perfect Squares?

Solution Approach:

1. Store the data in an array.

#include <bits/stdc++.h>using namespace std;int main(){    int n, count = 0;    cin >> n;    int a[n];    for (int j = 0; j < n; j++)    {        int numb;        cin >> numb;        a[j] = numb;    }

2. Use two nested loops to sum and calculate the square root using pow

#include <bits/stdc++.h>using namespace std;int main(){    int n, count = 0;    cin >> n;    int a[n];    for (int j = 0; j < n; j++)    {        int numb;        cin >> numb;        a[j] = numb;    }    for (int j = 0; j < n; j++)    {        for (int i = j + 1; i < n; i++)        {            int sum;            sum = a[i] + a[j];            int p;            p = pow(sum, 0.5);            (p * p == sum) ? count++ : count;        }    }    cout << count << endl;}

3. Here is a trick: After taking the square root, the result may be a decimal, but we need a perfect square. Therefore, we define the square root result as an integer p. Then we check if p * p equals the original number before taking the square root, which indicates that it is indeed an integer. We then increment the count.

            p = pow(sum, 0.5);            (p * p == sum) ? count++ : count;

Conclusion: If one approach does not work, return to the starting point and try again. If the forward approach is different, then adjust the direction to find a solution.Have you learned this?GESP Level 3 C++ Programming (50C++): How to Determine Perfect Squares?

Leave a Comment