- Sep 29, 2000
- 2,157
- 0
- 0
Okay, we have this programming lab assignment where we have to write a recursive function to find out the first 20 numbers that are both square and triangular and it has to do it in less than 60 seconds o a P3 550.
So I go on the web and do a google and come up with this recursive formula to find out all square triangular numbers:
a(n) = 34 * a(n - 1) - a (n - 2) + 2
so I just whip up a quick code and everythings working... whatever.
However, today, in our lecture, our lecturer basically said that we cant use any formulas that would not be apparent to somebody without any deep understanding in number theory and a friend of mine who had a Lab on Wednesday who used that formula did not get the mark. His lab teacher said that what he was doing was "black magic".
So, I have come up with a non-black magic solution where it says:
starting at n = 1, m = 1
if the nth square is larger than the mth triangular number, add one to m and repeat recursivly
if the nth square is less than the mth triangular number, add one to n and repeat recursivly
if m = n, print it out, add one to both m and n and keep going until you have printed out 20 numbers.
The problem is, the 20th square triangular number is 361786555939836 ^2 and my algorithm is doing roughly 400,000 numbers per minute so it would take roughly 700 years for me to get up to the 20th number this way.
Can anybody think of a faster way to run this task so that it could get under 60 seconds?
So I go on the web and do a google and come up with this recursive formula to find out all square triangular numbers:
a(n) = 34 * a(n - 1) - a (n - 2) + 2
so I just whip up a quick code and everythings working... whatever.
However, today, in our lecture, our lecturer basically said that we cant use any formulas that would not be apparent to somebody without any deep understanding in number theory and a friend of mine who had a Lab on Wednesday who used that formula did not get the mark. His lab teacher said that what he was doing was "black magic".
So, I have come up with a non-black magic solution where it says:
starting at n = 1, m = 1
if the nth square is larger than the mth triangular number, add one to m and repeat recursivly
if the nth square is less than the mth triangular number, add one to n and repeat recursivly
if m = n, print it out, add one to both m and n and keep going until you have printed out 20 numbers.
The problem is, the 20th square triangular number is 361786555939836 ^2 and my algorithm is doing roughly 400,000 numbers per minute so it would take roughly 700 years for me to get up to the 20th number this way.
Can anybody think of a faster way to run this task so that it could get under 60 seconds?