Project Euler #135: Same differences

  • + 0 comments

    Very easy mathematical solution: check the delta on two variable equations. There are solutions where delta is positive or zero, and there are integer solutions where delta is a perfect square of an integer. then simply calculate the solutions and be careful not to count the same solution twice by mistake. Unfortunately I am getting timeout at the last 5 tests even tho this is the fastest I have tried :/

    int solutions = 0;
            for(long double i = (sqrt(n/4)-fmod(sqrt(n/4),1)); i<=(n/4)+(1-fmod(n/4,1));i++)
            {
                if(is_perfect_square(4*i*i-n)){
                    long double x1 = 2*i -sqrt(4*i*i-n);//solution one
                    long double x2 = sqrt(4*i*i-n) +2*i;//solution two
                    
                    //solutions have to be bigger than the difference orelse Xs go negative
                    if(x1 > i){solutions++;}
                    if(x2 > i){solutions++;}
                    if(x1 == x2){solutions--;}//remove inserted duplicate solution where x1 = x2
                }       
            }