- 8051

GCD of two numbers using 8051 microcontroller.

This program finds the GCD of given two numbers and stores it in the register.

Algorithm.

1) Store the num1 in R1 register and num2 in R2 register.
2) Compare whether num1>num2 and directly store result if num1=num2.
3) If num1>num2 assign numerator register to num1 and denominator register to num2 otherwise assign numerator register to num2 and denominator register to num1 otherwise.
4) Store the remainder in remainder register.
5) Repeat step 3 until the remainder is zero.
6) Store the value of gcd to the denominator.

CODE:

      org 0000h
      ljmp main
      org 40h
main: mov R1,#09       ; The first number to find gcd
      mov R2,#06       ; The second number to find gcd
      mov a,R1
      mov b,R2
      cjne a,b,next    ; compares and jumps to assign proper registers
      ljmp stop        ; if two numbers are equal it assigns the same number to the result register
next: jnc loop         ; if num1>num2 it jumps to loop
      mov a,R2         ; if num1<num2 it assigns the registers in reverse way
      mov b,R1
loop: mov R3,b         ; temperorily storing the second register in r4
      div ab
      mov a,R3  
      mov R7,b         ; storing the remainder in r7
      cjne R7,#00h,loop; the loop repeats till the remainder is zero
stop : mov R4,a        ; Stores the result in r4
       end

Leave a Reply