Take the 2-minute tour ×

Let's say I have a number like 21 and I want to split it up so that I get the numbers 2 and 1.

To get 1, I could do 1 mod 10. So basically, the last digit can be found out by using mod 10.

To get 2, I could do (21 - (1 mod 10))/10.

The above techniques will work with any 2-digit number.

However, let me add a further constraint, that mod can only be used with powers of 2. Then the above method can't be used.

What can be done then?

share|improve this question
Why the restriction on mod? And does that mean you also can't use integer divisions? –  Mat Mar 11 '11 at 16:44
"mod can only be used with powers of 2" -- this smells like homework. –  larsmans Mar 11 '11 at 16:44
stackoverflow.com/questions/5189631/…. To get the answer for division as well as the remainder, you set the appropriate bit in the answer each time you do a subtraction. –  Jerry Coffin Mar 11 '11 at 16:52
Whichever way you slice it you're going to need an integer division routine. –  Paul R Mar 11 '11 at 16:57
The reason for the restriction is I'm actually trying to do this in Verilog, which has syntax very similar to C. If I disguised the question as a C question, I figured I would get better answers, and I was right. –  node ninja Mar 11 '11 at 17:11
add comment

3 Answers

up vote 5 down vote accepted
2 == 23 / 10
3 == 23 - (23 / 10) * 10
share|improve this answer
Note that this works because 23 / 10 is an integer division in C and so returns a rounded down integer (2). –  schnaader Mar 11 '11 at 16:44
add comment

To get 2 you can just do

int x = 23 / 10;

remember that integer division drops the fractional portion (as it can't be represented in an integer).

Modulus division (and regular division) can be used for any power, not just powers of two. Also a power of two is not the same thing as a two digit number.

To split up a three digit number

int first = 234/100;
int second = (234/10)-first*10;
int third = (234/1)-first*100-second*10;

with a little work, it could also look like

int processed = 0;
int first = 234/100-processed;
processed = processed + first;
processed = processed * 10;
int second = 234/10-processed;
processed = processed + second;
processed = processed * 10;
... and so on ...

If you put a little more into it, you can write it up as a loop quite easily.

share|improve this answer
add comment

what about

x%10 for the second digit and x/10 for the first?

share|improve this answer
he can't use 10 for the modulus, only powers of 2. reread the question. –  William Tate Mar 11 '11 at 16:43
You'll want to check that it is < 100 too. –  Douglas Mar 11 '11 at 16:45
The constraint that only powers of 2 are useable was added after I posted this answer. –  tgmath Mar 14 '11 at 15:01
add comment

Your Answer


