Skip to main content

Dual-purpose processor: factorial and prime

Short answer

The processor computes factorial by iterative multiplication (F=1, I=2..n) and checks primality by trial division with repeated subtraction. Datapath shares registers N, I, R, F, multiplier, subtractor; controller is a 10-state FSM with status flags le, lt2, ige, rge, rz.

Show the algorithm, FSMD, FSM, data-path, and controller design for a dual-purpose processor that can calculate the factorial of a number and also check if that number is a prime number.

Assumption: one 8-bit input n is read; the processor produces both outputs, FACT = n! and PRIME (1 if n is prime). Registers I and R are shared by both functions.

Algorithm

 read n
 F = 1
 for I = 2 to n: F = F * I        // factorial
 FACT = F
 if (n < 2) PRIME = 0
 else:
    I = 2
    while (I < n):
        R = n; while (R >= I) R = R - I
        if (R == 0) { PRIME = 0; stop }
        I = I + 1
    PRIME = 1
 output FACT, PRIME

FSMD

StateConditionActionsNext
S0start = 0waitS0
S0start = 1N = n; F = 1; I = 2S1
S1I <= NnoneS2
S1I > NFACT = FS3
S2alwaysF = F * I; I = I + 1S1
S3N < 2noneS9
S3N >= 2I = 2S4
S4I >= NnoneS8
S4I < NR = NS5
S5R >= InoneS6
S5R < InoneS7
S6alwaysR = R - IS5
S7R = 0noneS9
S7R != 0I = I + 1S4
S8 primealwaysPRIME = 1, done = 1S0
S9 not primealwaysPRIME = 0, done = 1S0

Note: n = 0 gives 0! = 1 and n = 1 gives 1.

FSM (control signals per state)

StateSignals
S0N_ld, F_set1, I_set2 (on start)
S1none (compare I <= N)
S2F_ld (multiplier), I_inc
S3FACT_ld (compare N < 2)
S4R_ld (R = N) when I < N
S5none
S6R_sub
S7I_inc when R != 0
S8PRIME = 1, done
S9PRIME = 0, done

Datapath

 n -> [N] --> comparators: I<=N, N<2, I>=N
 [F] <- mux(1, F*I) <- [ * multiplier ] <- F, I
 [I] <- mux(2, I+1) <- incrementer
 [R] <- mux(N, R-I) <- subtractor ; compare R>=I ; zero detect R==0
 [FACT] <- F ; [PRIME] flag

Components: registers N, F (16 or 32 bits for the factorial), I, R, FACT, PRIME flag; one multiplier, one incrementer, one subtractor; comparators (I <= N, N < 2, I >= N, R >= I) and a zero detector; four multiplexers.

Controller

Block diagram:

 start, status flags --> +-------------+   +-----------+
 (from datapath)         | Next-state  |-->| State     |
                         | logic       |   | register  |
                         +------^------+   +-----+-----+
                                |   current state |
                                +-----------------+
                                                  v
                                           +-------------+
                                           | Output logic|--> control
                                           +-------------+    signals

Inputs: start, status flags (le, lt2, ige, rge, rz). Outputs: loads, mux selects, done. 10 states (S0-S9): 4-bit binary state register.

All Embedded System chapter 2 questions →