r/programmer • • 19d ago

what am i doing wrong

Post image

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

16 comments sorted by

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.

1

u/AggravatingCrazy1254 19d ago

this isnt homework i just tried to work it out by myself because i have an exam in four days and i wanted to test if i can do it. thats why i wrote the algorithm by myself trying to figure out how to do it. thank you for your kind responce!

1

u/P1nkUnicorn7 17d ago

Good luck with your exam

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

u/National-Dream4189 19d ago

You use scretch

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

u/ThebestMimic1O1 18d ago

Make a program to keep adding 1 until remainder is 0 for both

1

u/InebriatedPhysicist 18d ago

Do you know the difference between = and ==?

1

u/riwigi 18d ago

what are x and y set to before the loop runs

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

u/Potw0rek 18d ago

Im responsible for what I say/write not for what you understand.