So I tried working out a solution to this problem, but my program is acting very strange.
#include <iostream>
using namespace std;
int triangle_numbers(int n, int meh = 0)
{
int count = 0;
//calculate how many divisors there are for meh
for(int i = 1; i <= meh; i++)
if(meh%i == 0)
count++;
//if the number of divisors for meh is over 500, return meh
if(count > 500)
return meh;
//recursive call to increment n by 1 and set meh to the next triangle number
triangle_numbers(n+1, meh += n);
}
int main()
{
int cc = triangle_numbers(1);
cout << cc << endl;
}
If I output meh and count individually I get accurate results, so I’m not sure why my program is giving me the same number (4246934) even if I do, say, if(count > 10). I have a feeling it may have to do with my recursive call, but everything I’ve tried so far hasn’t worked. Any help?
You are missing a final
returnstatement necessary to complete the recursion (doesn’t the compiler warn thattriangle_numbersdoes not actually return something in all cases?).Once the final value of
mehhas been computed, you need to haveso that
mehcan be returned all the way back up the call stack and finally tomain.The number you are seeing now is probably a value left over on the stack after the recursion does end.
Side note: a classic optimization in this algorithm is to have
iiterate up tomeh / 2but no further. Obviously numbers greater than half ofmehcannot evenly divide it so they can be skipped.