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.
- Store first number(num1) in a register
- Store second number(num2) in another register
- Initialize a counter register(Rd) to 01h
- 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
- 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
Here is example code to find LCM of 3 and 6
<br />ORG 0000h<br /> LJMP main<br /> ORG 0040h<br /> main: MOV R0,#03h ; Initializing first number<br /> MOV R1,#06h ; Initializing second number<br /> MOV R2,#01h ; Initializing counter register(Rd)<br /> MOV A,R0<br /> MOV B,R1<br /> CJNE A,B,label1 ; Comparing both numbers for equality <br /> MOV R4,A <br /> SJMP stop<br /> label1: JNC loop ; Comparing and swapping values if num1 is less than num2<br /> MOV A,R1<br /> MOV B,R0<br /> MOV R0,A<br /> MOV R1,B<br /> loop: MOV A,R2 ; loop to find LCM<br /> MOV B,R0<br /> CJNE A,B,next ; comparing if Rd value and num1 are equal<br /> SJMP stop<br /> next: MOV A,R1 ; Finding product of num2 and Rd<br /> MOV B,R2<br /> MUL AB<br /> MOV R4,A ; Storing product <br /> INC R2<br /> MOV B,R0<br /> DIV AB ; Dividing by num1 to find reminder<br /> MOV R3,B<br /> CJNE R3,#00h,loop ; Continue until reminder becomes zero<br /> SJMP stop<br /> stop: JMP stop<br />END<br />