- 8051

8051 code to find Permutation and Combination

This program finds the value of permutation and combination for given two input numbers

 Algorithm

1) Store the value of n to R0,store the value of r to R1 and store the value (n-r) to R2.
2) Compare if n>r continue the process, if n<r then stop computation, if n=r then assign permutation as n! and combination as 1.
3) Calculate the n!,r!,(n-r)! and store in R3,R4,R5 respectively.
4) Calculate permutation by dividing n!/(n-r)!
5) Calculate combination by dividing n!/(n-r)!*r!

Code goes here:

org 0000h
ljmp main
org 40h
main:          MOV R0,#04 ; value of n
               MOV R1,#02 ; value of r
               MOV A,R0
               MOV B,R1
               CJNE A,B,CHECK ; to check whether n is greater than r
               LJMP COMPUTE
CHECK:         JC STOP         ; jump to stop if n<r
               SUBB A,R1
               MOV R2,A        ; the value of n-r
               MOV A,R0
LABEL1:        DEC R0
               MOV B,R0
               MUL AB
               CJNE R0,#01,LABEL1
               MOV R3,A        ; the value of n!
               MOV A,R1
LABEL2:        DEC R1
               MOV B,R1
               MUL AB
               CJNE R1,#01,LABEL2
               MOV R4,A        ; the value of r!
               MOV A,R2
LABEL3:        DEC R2
               MOV B,R2
               MUL AB
               CJNE R1,#01,LABEL3
               MOV R5,A        ; the value of n-r!
               MOV A,R3
               MOV B,R5
               DIV AB         ; dividing n!/(n-r)!
               MOV R6,A        ; storing the result of permutation
               MOV B,R4 
               DIV AB          ; dividing n!/(n-r)!*r!
               MOV R7,A        ; storing the result of combination
               LJMP STOP
COMPUTE:       DEC R0         ; it stores the value of permutation=n! if n=r
               MOV B,R0
               MUL AB
               CJNE R0,#01,LABEL1
               MOV R6,A        ; the result of permutation=n! if n=r
STOP:          MOV R7,#01      ; it stores the value of combination=1 if n=r
    END

Leave a Reply