I made a program of hofstarder q sequece but the output is working till 32 only | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I made a program of hofstarder q sequece but the output is working till 32 only

Hofstadter's Q-Sequence is a sequence of numbers where every integer above zero has a corresponding q-sequence value. You can determine the q-sequence value from a formula that tells you how far back in the sequence to go and add two values together. The first two values of the sequence are Q(1) = 1 and Q(2) = 1, and every number above 2 can be expressed according to the following formula (where n is your input value): Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n -2)) Task: Given an integer value input, determine and output the corresponding q-sequence value. Input Format: A positive integer value. Output Format: A positive integer value that represents the value in the q-sequence that the input holds. Sample Input: 5 Sample Output: 3 https://code.sololearn.com/c2idzIj3JoNY/?ref=app https://code.sololearn.com/c2idzIj3JoNY/?ref=app

16th Apr 2020, 9:19 AM
Ashwani Kumar
Ashwani Kumar - avatar
1 Answer
+ 1
Your program uses recursion to calculate all numbers and every number is dependent on every single number before it in the sequence. The trouble with recursion is that, in order ti calculate any number in the sequence, it has to re-calculate every number before it. This is a very time-consuming and wasteful method of doing this task. The easiest way to correct this is to save each number as you calculate into a list. Then every number needed to calculate all further numbers will be there ready to be looked up, rather than having to be re-calculated again.
16th Apr 2020, 3:38 PM
Russ
Russ - avatar