hunterr_196's blog

By hunterr_196, history, 6 years ago, In English

Here is the problem QUESTION. My approach :- I am taking the Nth root of the given no X and then storing the Nth power of that numbers in an array.

for ex :- x = 100, n = 3 then nth root is 4 and now storing Nth power 1,8,27,64 into an array. Now the main part comes where i am choked. I am unable to write down the code for counting that how many pair of numbers when added give me the number X. specially without using recursion and also didn't get the solution given in the above question link.

Can anyone please help me out through this by explaining that what is the actual concept I have to apply to solve this kind of problems. If possible please explain without using recursion and by using my approach if it is an efficient way to solve this problem. Thank you.

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

So you are saying that you don't get solution from the link. I think you should start with this before going any further, like trying to use some gimmicky non-recursive version :) So try to take paper and pen, take the test from example (x=10, n = 2) and "execute" code on paper — i.e. write down all the values of "curr_num", "p", "curr_sum" variables, depth of recursion, when "results" is changing. I think that's the best approach to understand this code. I can start for you (numbers in the row are

depth of recursion, curr_sum, curr_num, p):

1 0 1 1

2 1 2 4

3 5 3 9 // here we can see that p + curr_sum >= x (5 + 9 >= 10), so we won't go into "while", later we will check that p + curr_sum != x, so we won't add to result and we will go back in recursion

2 1 3 9 // here p + curr_sum >= x (1 + 9 >= 10), so we won't go into "while", but actually p + curr_sum == x, so we will increase results and we have our first solution 1^2 + 3^2 == 10, now we go back in recursion again

1 0 2 4

If you don't understand something about my idea please ask questions. If everything is clear then try to do this alone and come back with your rows written down so I can check if you got it.