Project Euler #98: Anagramic squares

Sort by

recency

|

20 Discussions

|

  • + 0 comments

    C++

    #include <bits/stdc++.h>
    using namespace std;
    
    long hashVal[10];
    
    long Hash(string &s)
    {
        long res = 0;
        int count[10] = {0};
        
        for(int i=0; i<s.size(); i++)
        {
            int c = s[i]-'0';
            count[c]++;
            res += (count[c] * hashVal[c]);
        }
        return res;
    }
    
    int main() 
    {    
        for(int i=0; i<10; i++)
        {
            hashVal[i] = (i+1) * (rand() % 11587);
        }
        
        int N;
        cin >> N;
    
        vector<int> M(100000010);
        
        string square, digits;  
        int maxCount = 0;            
        
        long long i = sqrt(pow(10, N-1));
        long long end = floor(sqrt(pow(10, N)));
        long long s, ans;
        
        for(; i<=end; i++)
        {           
            s = i*i;
            
            square = to_string(s);        
            digits = square;
            sort(digits.begin(), digits.end());
                   
            long index = Hash(digits);
                    
            M[index]++;
    
            if(M[index] > maxCount)
            {           
                maxCount = M[index];
                ans = s;
            }      
        }
        cout << ans << endl;
        return 0;
    }
    
  • + 1 comment

    Only test case 10 fails due to timeout error. I tried submitting in pypy3 too. Annoying. Any help?

  • + 0 comments

    why is test case 0 is failing and rest all are passing? isn't the testcase with N=4? i am able to test my code for N=4 with correct answer of 9216. I am not sure what am i missing.

  • + 1 comment

    Hints:

    1) For each N, you only need to loop from 10^((N-1)/2) to 10^(N/2). For example: N=4, i runs from 31 to 100. Then take i^2. That saves a lot of time complexity compared with i running from 1000 to 10000 and then taking square root.

    2) A nice trick to store all permutations in any permutation problems: create a dictionary, convert satisfied number as a sorted key. For example: {'1269': [1296, 2916, 9216]}, where '1269' is sorted key of 1296, 2916 and 9216

  • + 0 comments

    I followed a simpler approach, I precomputed all the answers and stored it, and just responded to the queries...

    for the hash function i used the descending order of digits.