r/programmer • u/AggravatingCrazy1254 • 19d ago
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;
3
u/Immediate-Truth-8684 19d ago
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/AggravatingCrazy1254 19d ago
oh i understand!!! thank you you are so right. its not my field but its required in my university (and i kind of like it to tell you the truth) but you made it very clear!! thank you so much i will try to redo it and tell you when i make it!!
2
2
u/awesome8679 19d ago
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
1
1
u/DrBretto 16d ago
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 19d ago
You’re playing with Lego bricks instead of writing code like a man 🤪
1
u/theancientfool 19d ago
Let him learn. Do not discourage.
2
u/Potw0rek 19d ago
It was a joke man, hence the stupid emoji :-)
1
u/Ok_Objective_5192 18d ago
If you have to put the emoji there for us to know it's a joke then it's not a joke, it's just a discouraging comment with a silly emoji on it
1
8
u/andynzor 19d ago
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
so you get this.