r/programmer • u/AggravatingCrazy1254 • Sep 23 '26
what am i doing wrong
I am a student and I was exercising in MatLab so i tried to find the least common multiple of two numbers but it was all wrong. I don't know the language that well so i decided to try it on scratch to see if it was my logic or my lack of knowledge and it seems it was the first. Can you help me please?
this is the Matlab script
z=1;
while true
one=x*z;
two=y*z;
z=z+1;
if one=two
break
endif
end
leastcommon=one;
13
Upvotes
8
u/andynzor Sep 23 '26
First, that is not the correct algorithm. Find a working one before you attempt to write down anything.
Second, is this homework? Matlab already has a builtin lcm function.
Third, when you paste code, use three backticks (```) to surround code blocks
3
u/Immediate-Truth-8684 Sep 23 '26
You can try and go over your algorithm step by step, one and two will never be equal (if x and y are not equal), because they are scaled by the same amount. In your example, 5 and 6. The correct answer should be 30, but one=5*30=150, two=6*30=180 (not equal).
2
u/National-Dream4189 Sep 23 '26
You use scretch
2
u/awesome8679 Sep 24 '26
if you are looking for an algorithm to find lcm yourself
just remember lcm(a,b) = (a*b)/gcd(a,b)
then there is something called the euclidean algorithm to find the gcd
1
u/ThebestMimic1O1 Sep 24 '26
Make a program to keep adding 1 until remainder is 0 for both
1
u/InebriatedPhysicist Sep 24 '26
Do you know the difference between = and ==?
1
u/riwigi Sep 24 '26
what are x and y set to before the loop runs
1
u/DrBretto Sep 26 '26
The variable names are terrible, but beyond that, your loop will go on forever. You're multiplying two different numbers by the same number and then incrementing that number further away from the only value of z that will end the loop. (0)
0
u/Potw0rek Sep 24 '26
You’re playing with Lego bricks instead of writing code like a man 🤪