MATLAB: How can i modify the code to do to find the smallest triangle number whose digits add up to N

if statementMATLABwhile loop

function [T]= MyFunction(N)
tN=0;
n=1;
dSum=0;
while dSum<N-1
tN=tN+n;
n=n+1;
dSum=0;
num=tN;
while num>0
dSum=dSum+mod(num,10);
num=floor(num/10);
end
end
T = tN;
end
Your function needs to find the smallest triangle number whose digits add up to N and return this triangle number as T.
Example input:
N=10
Example output:
T=28
In this case, T=28 is the 7th triangle number (1+2+3+4+5+6+7=28), and the digits of T add up to (2+8)=10 = N

Best Answer

What is wrong with the code as it is? Why do you think it does not work? When does it fail? What characteristic of T can you see that causes the loop to fail?
Perhaps the problem might be partly in the while loop itself. We see this:
while dSum<N-1
However, will the while loop terminate if dSum happens to be greater than N? Would that be a problem? What if dSum was exactly equal to N-1? The target is N, not N-1 anyway.
There is a not equal to operator in MATLAB.
while dSum ~= N
Would this help?
When you see a problem in the code, look at what the code produces. Think about how it might fail. Using the debugger is a GREAT tool to investigate problems like this.