We write a program that finds a positive n number of integers. So, if all the integers from 1 to n in the form 1 + 2 + 3 + ⋯ + n are summed up, the result is between 100 and 1000. At the same time, the three numbers of this sum are the same (like 333

2 views (last 30 days)
We write a program that finds a positive n number of integers. So, if all the integers from 1 to n in the form 1 + 2 + 3 + ⋯ + n are summed up, the result is between 100 and 1000. At the same time, the three numbers of this sum are the same (like 333). Print the integer and sum of the program as output.

Answers (2)

Cam Salzberger
Cam Salzberger on 15 May 2017
So you could solve this with a complete brute-force method, but let's not because that's no fun. If I were to approach this problem, I would first check out what the mathematical expression is for 1+2+...+n. There's a convenient Wikipedia article on this showing that it's n(n+1)/2.
So now you know that given the total value, you can solve for the roots of this equation to get n:
0 = (n^2 + n -2*total)
or
n = roots([1 1 -2*total])
And you know your desired possible total values (111, 222, ..., 999). So if I were doing this just in the Command Window, I would run that through a loop, solving for n for each value:
s = [111 222 333 444 555 666 777 888 999];
for k = 1:length(s)
roots([1 1 -2*s(k)])
end
And then just see which of the (positive) n values was an integer. Double-check this with sum(1:n).
Now to automate it, you'd just have to automate the finding of which value is an integer. This is pretty simple to do with mod or floor, so I'll leave it to you.
Hope this helps!
-Cam

ramazan araz
ramazan araz on 17 May 2017
What does the 'tal' that you use in the beginning cover?
  2 Comments
Cam Salzberger
Cam Salzberger on 17 May 2017
I didn't use 'tal' anywhere, so I assume you are talking about "total". This is representing the "all summed up" value in the question. For this case, we know we want the total to be 111, 222, 333, ..., or 999.
John D'Errico
John D'Errico on 17 May 2017
Please don't add an answer just to make a comment. As you see, it is very simple to make a comment. Use that instead.

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!