Theory:The factorial of a positive integer n, denoted as n!, is the product of all positive integers from n down to 1.
n!=n×(n−1)×(n−2)×⋯×1n! = n \times (n-1) \times (n-2) \times \cdots \times 1n!=n×(n−1)×(n−2)×⋯×1
Block diagram:
Verilog code:
module factorial_calculator (
input wire [2:0] n,
output reg [12:0] factorial
);
integer i;
always @(*) begin
factorial = 1;
i = n;
while (i > 0) begin
factorial = factorial * i;
i = i - 1; // Decrement i
end
end
endmodule
Test bench:
module factorial_tb;
reg [2:0] n;
wire [12:0] factorial;
factorial_calculator uut (
.n(n),
.factorial(factorial)
);
initial begin
$monitor("Time=%t, n=%d, fact=%d", $time, n, factorial);
n = 3; #10;
n = 4; #10;
n = 5; #10;
$finish;
end
endmodule
Output:
Device utilization:
Time analysis: