2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. Write a function called smallest_multiple that returns a uint64, the smallest positive number that is evenly divisible by all of the numbers fr
7 views (last 30 days)
Show older comments
I keep getting an error everytime I run my code that says:
[out] = smallest_multiple(6)
Error using gcd (line 23)
Inputs must be floats, namely single or double.
Error in smallest_multiple (line 4)
out = (out * i) / (gcd(out,i));
Is 6 not a single?
Here is my code:
function [out] = smallest_multiple(n)
out = uint64(1);
for i = 1 : n
out = (out * i) / (gcd(out,i));
end
if out >= intmax('uint64')
out = uint64(0);
end
end
5 Comments
Accepted Answer
More Answers (2)
Rik
on 8 Jan 2019
There is an important difference between a single value (called a scalar in Matlab), and a value of data type single (which is an array that is stored in a specific format internally).
The gcd function requires the input to be a double or a single, so you should either keep it as a single/double or force it to be one, either with the cast function or by executing double(out).
10 Comments
Rik
on 9 Jan 2019
Glad to hear you found a solution.
Do you need your code to work until a larger value? You might need to rework your algorithm. Another method of solving this question might be to check the prime factors and use ismember.
Emma Sellers
on 10 Jan 2019
5 Comments
Steven Lord
on 10 Jan 2019
That answer is not correct. There are several ways to see this. The first is to try the division.
x = uint64(409927646082434480)
d = x/3;
d2 = 3*d;
check = [x; d2]
If x were divisible by 3, the two elements in check would be the same. They aren't.
The sum of the digits in x is 80, which is another sign the answer is incorrect. The divisibility rule for 3 is that the sum of the digits must itself be a multiple of 3.
A third check is that the result must be divisible by both 25 (=5^2) and 4 = (2^2) so it must be a multiple of 100 (=2^2 * 5^2).
At this point, I think you've done your due diligence and should probably talk to your professor or teaching assistant. Do they expect you to do the calculations symbolically and check afterward if it's too large to fit in a 64-bit integer? Do they expect you to perform the calculations iteratively and stop as soon as the next one would saturate? It's not quite clear from the snippet of the assignment in the title of this post.
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!