-4

I'm working on a Uva problem (#107) and I know I have the right answer, and now I just need to optimise it so it doesn't time out. I believe this snippet is the culprit. I need to find n and k such that n^k = working. I tried making my own power function to speed it up but that didn't help. What are some ways to quickly calculate a base and exponent to equal a given value?

N = 2;
for(int i = 1; i < range; i++){
    result = pow(N, i);

    if(result > working){
        i = 1;
        N++;
    }

    if(result == working){
        k = i;
        break;
    }
}

1 Answers1

0

You can try k >= 2 and limit N with sqrt(w), start i with 2 in the loop. If solution is not found then k = 1, n = w. Also you do not need pow, you could multiply intermediate product by N on each iteration.

273K
  • 29,503
  • 10
  • 41
  • 64