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<iostream>#include<vector>#include<map>//#define ORIGINAL// a single addition chaintypedefstd::vector<unsignedint>Chain;// iterative depth-first search of Brauer sequenceboolsearch(Chain&chain,unsignedintexponent,unsignedintmaxDepth){// too deep ?if(chain.size()>maxDepth)returnfalse;autolast=chain.back();for(size_ti=0;i<chain.size();i++){//auto sum = chain[i] + last;autosum=chain[chain.size()-1-i]+last;// try high exponents first => about twice as fastif(sum==exponent)returntrue;chain.push_back(sum);if(search(chain,exponent,maxDepth))returntrue;chain.pop_back();}returnfalse;}// increase depth until a solution is foundChainfindChain(unsignedintexponent){// cached ? (needed for Hackerrank only)staticstd::map<unsignedint,Chain>cache;autolookup=cache.find(exponent);if(lookup!=cache.end())returnlookup->second;// start iterative searchChainchain;unsignedintdepth=1;while(true){// reset chainchain={1};// a start searchif(search(chain,exponent,depth))break;// failed, allow to go one step deeperdepth++;}cache[exponent]=chain;returnchain;}// print a single chain in Hackerrank formatvoidprint(constChain&chain){// number of multiplicationsstd::cout<<(chain.size()-1)<<std::endl;// print each multiplicationfor(size_ti=1;i<chain.size();i++){// involved exponentsautosum=chain[i];autoadd1=chain[i-1];autoadd2=sum-add1;std::cout<<"n";if(add1>1)std::cout<<"^"<<add1;std::cout<<" * n";if(add2>1)std::cout<<"^"<<add2;std::cout<<" = n^"<<sum<<std::endl;}}intmain(){#ifdef ORIGINALunsignedintsum=0;// find all chains 2..200for(unsignedintexponent=2;exponent<=200;exponent++){autochain=findChain(exponent);// sum of all chains' lengthssum+=chain.size();}std::cout<<sum<<std::endl;#elseunsignedinttests;std::cin>>tests;while(tests--){unsignedintexponent;std::cin>>exponent;// compute one chain (there might be different chains of the same length)autochain=findChain(exponent);// append the exponent, which is not part of the chain yetchain.push_back(exponent);// and displayprint(chain);}#endifreturn0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #122: Efficient exponentiation
You are viewing a single comment's thread. Return to all comments →
100/- Points C++ Code