We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#include<vector>#include<iostream>#include<algorithm>// return true if x is a palindromeboolisPalindrome(unsignedintx){autoreduced=x/10;autoreverse=x%10;// fast exit: a trailing zero can't create a palindromeif(reverse==0)returnfalse;while(reduced>0){// chop off the lowest digit and append it to "reverse"reverse*=10;reverse+=reduced%10;reduced/=10;}// palindrome ? both must be equalreturnreverse==x;}intmain(){unsignedinttests=1;std::cin>>tests;while(tests--){unsignedintlimit=100000000;unsignedintstride=1;// distance between consecutive square numbersstd::cin>>limit>>stride;std::vector<unsignedint>solutions;for(unsignedlonglongfirst=1;2*first*first<limit;first++){autonext=first+stride;// sum of a^2 + b^2 + ...autocurrent=first*first+next*next;// still within the limit ?while(current<limit){// checkif(isPalindrome(current))solutions.push_back(current);// add one element to the sequencenext+=stride;current+=next*next;}}// sort ...std::sort(solutions.begin(),solutions.end());// .. and remove duplicatesautogarbage=std::unique(solutions.begin(),solutions.end());solutions.erase(garbage,solutions.end());// count all solutionsunsignedlonglongsum=0;for(autox:solutions)sum+=x;std::cout<<sum<<std::endl;}return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #125: Palindromic sums
You are viewing a single comment's thread. Return to all comments →
100/- Points C++