A give number x is \'good\' if the sum of any two consecutive digit of the number x are between k and 2k. I need to find an algorithm that for a given number k and a given numbe
All those calls to pow
certainly won't be helping.
What you can do is make a mapping of all the two-digit numbers that are 'good'. Once you have your mapping, all you need to do is check that every pair of digits in your number is good. You can do this by successive division by 10 and modulo 100.
Something like this would do the trick, provided you don't give it a negative number, and assuming you've set up your $good
array.
function isgood( $num ) {
while( $num >= 100 && $good[$num%100] ) {
$num /= 10;
}
return $good[$num%100];
}
The next most obvious thing to do is memoize larger sequences. This is a dynamic programming principle. We've already memoized small sequences by storing the 'goodness' of 2-digit sequences. But you could easily use those to generate sequences of 3, 4, 5, 6 digits... Whatever your available memory allows. Use the memos you already have in order to generate the sequences with one extra digit.
So, if you built up memoisation for up to 5-digit numbers, then you divide by 1000 every time, and get a great speedup.