Continue to Site

# Factorial of a no

Status
Not open for further replies.

#### ElectronicsDevil

##### New Member
I m having trouble with keil for 89c51. I want to find out factorial of a no. On keil. No are from 0-9. When the answer is greater than 255 we need to split the term in 2 memory locations but i dont know how it can be done.can anyone help me plz....

Since your numbers are from 0-9, the factorial result can go up to 362880 (factorial of 9), which I think will require more than 2 memory locations. One way is to store individual digits (ones, tens, hundreds, ...) to different locations. You can do that by dividing by 10 and saving the reminder.

- Raj
Experiments with PIC16F628A

Hey, I made what you need. This program receive in N the number which you want its factorial and give to you in D2,D1 and D0 the most, medium and less significant byte of the result (factorial of 9 is a 3 byte number). Hope you like it
Code:
N EQU 40H
D0 EQU 41H
D1 EQU 42H
D2 EQU 43H

AUX0 EQU 44H
AUX1 EQU 45H
AUX2 EQU 46H

ORG 0
FACTORIAL:
MOV A,N
MOV D0,#1
MOV D1,#0
MOV D2,#0

JNZ CHECA_FACT
RET

CHECA_FACT:	MOV A,N
CJNE A,#1,CONT_FACT2
RET
CONT_FACT2:	CALL MULTIPLICA
DEC N
JMP CHECA_FACT

MULTIPLICA:	MOV AUX0,#0
MOV AUX1,#0
MOV AUX2,#0

MOV A,D0
MOV B,N
MUL AB
CALL SUMA
MOV A,D1
MOV B,N
MUL AB
CALL SUMA2
MOV A,D2
MOV B,N
MUL AB
CALL SUMA3

MOV D0,AUX0
MOV D1,AUX1
MOV D2,AUX2
RET

MOV AUX0,A
MOV A,B
MOV AUX1,A
MOV A,AUX2
MOV AUX2,A
RET

SUMA2:
MOV AUX1,A
MOV A,B
MOV AUX2,A
RET

SUMA3:
MOV AUX2,A
RET

Status
Not open for further replies.

Replies
31
Views
4K
Replies
2
Views
5K
Replies
2
Views
3K
Replies
1
Views
7K
Replies
6
Views
9K