Hi; What is wrong in my code

2 次查看(过去 30 天)
SULE SAHIN
SULE SAHIN 2017-10-30
If we list all the natural numbers up to 15 that are multiples of 3 or 5, we get 3, 5, 6, 9, 10, 12 and 15. The sum of these multiples is 60. Write a function called sum3and5muls that returns the sum of all the unique multiples of 3 or 5 up to n where n is a positive integer and the only input argument of the function. (Credit: Project Euler)
My answer is;
function sumof = sum3and5muls(n)
sumof = sum([3:3:n])+sum([5:5:n])-sum([15:15:n]);
Fault; Problem 8 (sum3and5muls): Testing with argument(s) 1 Feedback: Your program made an error for argument(s) 1
Your solution is _not_ correct.
What is wrong in my code?
  4 个评论
Stephen23
Stephen23 2017-10-30
@SULE SAHIN: you do not need to use square brackets, because you are not concatenating anything. Instead of this sum([3:3:n]) you simply need this sum(3:3:n).
Walter Roberson
Walter Roberson 2018-4-27
Please do not close questions that have an answer.

请先登录,再进行评论。

回答(1 个)

Jan
Jan 2017-10-30
编辑:Jan 2017-10-30
The error message tells you, that the output for n=1 differs from the expectations. Look what your code does in this case. What is 3:3:n then? What is its sum?
What happens for n=3?
3:3:n
5:5:n
15:15:n
What might be the result of:
3 + [] - []
???
Note: 3:3:n is a vector already. There is no need fro additional square brackets, see http://www.mathworks.com/matlabcentral/answers/35676-why-not-use-square-brackets

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by