Write a function called smallest_multiple

6 Ansichten (letzte 30 Tage)
RUTARAKA GIDEON
RUTARAKA GIDEON am 4 Mär. 2018
Bearbeitet: Walter Roberson am 3 Jun. 2018
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 from 1 to n where n is a positive integer scalar and is the only input argument of the function. If the result would be greater than what can be represented as a uint64, the function returns 0.

Antworten (2)

Image Analyst
Image Analyst am 4 Mär. 2018
Here is a hint:
function results = smallest_multiple(n)
% Your code goes here
Next step, read this:

Srishti Saha
Srishti Saha am 13 Mai 2018
Here is a solution that worked for me:
%%alternative solution to smallest multiple
function r = smallest_multiple(k)
r = uint64(1);
for n = 1:k
r = r * (n / gcd(r,n));
end
if r == intmax('uint64')
r = uint64(0);
end
end
  4 Kommentare
Walter Roberson
Walter Roberson am 13 Mai 2018
Bearbeitet: Walter Roberson am 3 Jun. 2018
The test is okay except for the case where the smallest multiple is exactly equal to intmax('uint64') which is 18446744073709551615 = 65537*(641*(17*(3*5)*257)*6700417) .
In any case where the result would be bigger than intmax('uint64') then the multiplications in the for loop would "saturate" at exactly intmax('uint64')
Ranil Fernando
Ranil Fernando am 3 Jun. 2018
Bearbeitet: Ranil Fernando am 3 Jun. 2018
My code is working outside the grader for n=13 without taking a longer time. But within the grader it fails for even 2. Someone please give me a hand here.
function multiN = smallest_multiple(n)
mod2N = 0;
multiN = uint64(n);
while all(mod2N) == 0
multiN = multiN + 1;
mod2N = zeros(1,n);
for ii=1:n
if mod(multiN,ii) == 0
mod2N(ii) = 1;
elseif multiN == intmax('uint64')
multiN = uint64(0);
end
end
end

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by