In this HackerEarth Perfect Subarray problem solution, You are given an array A of N integers. You need to count the subarrays which have the sum of all elements in it a perfect square.


HackerEarth Perfect Subarray problem solution


HackerEarth Perfect Subarray problem solution.

#include<bits/stdc++.h>
#define LL long long int
#define M 1000000007
#define endl "\n"
#define eps 0.00000001
LL pow(LL a,LL b,LL m){LL x=1,y=a;while(b > 0){if(b%2 == 1){x=(x*y);if(x>m) x%=m;}y = (y*y);if(y>m) y%=m;b /= 2;}return x%m;}
LL gcd(LL a,LL b){if(b==0) return a; else return gcd(b,a%b);}
LL gen(LL start,LL end){LL diff = end-start;LL temp = rand()%start;return temp+diff;}
using namespace std;
LL sum[100001];
int a[100001];
bool f(LL n){
    LL temp = sqrt(n);
    if(temp * temp == n){
        return 1;
    }
    ++temp;
    if(temp * temp == n){
        return 1;
    }
    return 0;
}
int main()
    {
        ios_base::sync_with_stdio(0);
        int n;
        cin >> n;
        assert(n >= 1 && n <= 3000);
        for(int i = 1; i <= n; i++){
            cin >> a[i];
            assert(a[i] >= 1 && a[i] <= 1000000);
            sum[i] = sum[i - 1] + a[i];
        }
        int ans = 0;
        for(int i = 1; i <= n; i++){
            for(int j = i; j <= n; j++){
                if(f(sum[j] - sum[i - 1]))
                    ++ans;
            }
        }
        cout << ans; 
    }

Second solution

#include <bits/stdc++.h>

using namespace std;

const int N = 5E3 + 5;
int a[N];

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n;
    cin >> n;
    for(int i = 0; i < n; i ++)
        cin >> a[i];
    int ans = 0;
    for(int i = 0; i < n; i ++) {
        double total = 0;
        for(int j = i; j < n; j ++) {
            total += a[j];
            double chkr = total;
            chkr = sqrt(chkr);
            if(chkr == floor(chkr))
                ans ++;
        }
    }
    cout << ans;
    return 0;
}