- 8051

8051 Assembly code to find LCM of two numbers

Hello guys! After lot of optimization and debugging finally found a ALP program to find LCM of two numbers using 8051 micro-controller. Happy share this piece of code with you guys.

            Its easy and short. We have been learning to find LCM from our school days. Finding Least common multiple of of two numbers is easy by finding GCD of those two numbers and then dividing of product of those two number by GCD. But in terms of programming its complicated! So, here I have new algorithm to find LCM of two numbers.
 ALGORITHM:

  1. Start
  2. Store first number(num1) in a register
  3. Store second number(num2) in another register
  4. Initialize a counter register(Rd) to 01h
  5. Compare both the values num1 and num2
    • If num1 = num2 : Store num1 or num2 as result and jump to step 8
    • If num1 < num2 : Swap the register values so that num1 > num2
  6. Multiply num2 and Rd and divide the product with num1
  7. Check the reminder
    • If reminder is zero then store product obtained from multiplication in step 6 as result and jump to step 8
    • Else increment Rd and repeat steps 6 and 7
  8. Stop

Here is example code to find LCM of 3 and 6

 CODE:


ORG 0000h
LJMP main
ORG 0040h
main: MOV R0,#03h ; Initializing first number
MOV R1,#06h ; Initializing second number
MOV R2,#01h ; Initializing counter register(Rd)
MOV A,R0
MOV B,R1
CJNE A,B,label1 ; Comparing both numbers for equality
MOV R4,A
SJMP stop
label1: JNC loop ; Comparing and swapping values if num1 is less than num2
MOV A,R1
MOV B,R0
MOV R0,A
MOV R1,B
loop: MOV A,R2 ; loop to find LCM
MOV B,R0
CJNE A,B,next ; comparing if Rd value and num1 are equal
SJMP stop
next: MOV A,R1 ; Finding product of num2 and Rd
MOV B,R2
MUL AB
MOV R4,A ; Storing product
INC R2
MOV B,R0
DIV AB ; Dividing by num1 to find reminder
MOV R3,B
CJNE R3,#00h,loop ; Continue until reminder becomes zero
SJMP stop
stop: JMP stop
END

Leave a Reply