summaryrefslogtreecommitdiff
path: root/collatz.v
blob: e90c1bde372c1ce9ea6a70596374ed09c4f6c447 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
module collatz (
  input clk,
  input rst,

  input wire [15:0] in_start,
  input wire start_int,

  output reg [15:0] o_count,
  output finish_int
);

  localparam IDLE = 0;
  localparam SPINNING = 1;
  localparam WAIT_TICK = 2;

  reg [1:0] state = 0;
  reg [15:0] count = 0;
  reg [15:0] n = 0;

  wire is_even;

  assign is_even = ~n[0]; 
  assign finish_int = (n == 1 && state == IDLE);

  always @(posedge start_int) begin
    if (state == IDLE) begin
      state <= SPINNING;
      n <= in_start;
    end
  end

  always @(posedge clk or posedge rst) begin
    if (rst == 1'b1) begin
      state <= IDLE;
      count <= 0;
      n <= 0;
    end else if (state == IDLE) begin
      n <= 0;
    end else if (state == SPINNING) begin
      if (n <= 1) begin
        o_count = count;
        state = WAIT_TICK;
        // finish_int should be triggered.
      end else begin
        if (is_even) begin
          n <= n >> 1;
        end else begin
          n <= n * 3 + 1;
        end
        count <= count + 1;
      end
    end else if (state == WAIT_TICK) begin
      state <= IDLE;
    end
  end

  endmodule