I want to work with residue number system and make an ALU based on residue number system. So frequently I need to calculate the remainder and using modulo operator is not helping as it is not synthesizable.


closed as unclear what you're asking by Eugene Sh., pipe, RoyC, Edgar Brown, Finbarr Jan 25 at 10:09

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\begingroup\$ What is the range of numbers you want to divide by 5? \$\endgroup\$ – Eugene Sh. Jan 21 at 17:28
  • \$\begingroup\$ You can implement a divider (and thus modulo operation) by writing a divider state-machine. If this goes in an FPGA: some vendors offer a divider block as IP. Others, I have been told, DO allow the divider operator in their latest SW revision. (p.s. You did not actually ask a question and "I" should be a capital) \$\endgroup\$ – Oldfart Jan 21 at 17:30

5 is a bit of an unhelpful number when it comes to binary arithmetic. Fortunately however, it is a nice factor of 15.

15 is known as a Marsenne number - that is a number which is one less than a power of two (15 = 24-1). A nice property of Marsenne numbers is that you can perform modulo in binary without using any division.

The following code should work for numbers up to 32bit:

module modulo5(
    input  [31:0] numIn,
    output [ 2:0] result
    wire [16:0] partOne   =   numIn[31:16] +         numIn[15:0];
    wire [ 9:0] partTwo   = partOne[16: 8] + {1'b0,partOne[ 7:0]};
    wire [ 5:0] partThree = partTwo[ 9: 4] + {1'b0,partTwo[ 3:0]};

    //Final step is to convert into modulo 5.
    //Because the result is limited in size, we can find this by a simple lookup table.
    //This should optimise into a single 6-bit LUT for each of the three output bits.

    reg [2:0] partFour [63:0];
    integer i;
    initial begin
        for (i = 0; i < 63; i = i + 1) begin
            partFour[i] = i % 5;

    //And the result
    assign result = partFour[partThree];

The final section is a simple lookup table. As the input was reduced to only 6-bit, that stage can be realised with three 6-bit LUTs so is actually incredibly efficient.

If your input was only up to 10-bit, you could skip parts one and two. For inputs up to 17-bit you can skip part one.


Make a state machine that repeatedly subtracts 5 from the value in question, stopping when the result is less than 5. Without more information from you that's the most generic suggestion I can make.


Not the answer you're looking for? Browse other questions tagged or ask your own question.