Check if a number is divisible by 3 [closed] - puzzle

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
Write code to determine if a number is divisible by 3. The input to the function is a single bit, 0 or 1, and the output should be 1 if the number received so far is the binary representation of a number divisible by 3, otherwise zero.
Examples:
input "0": (0) output 1
inputs "1,0,0": (4) output 0
inputs "1,1,0,0": (6) output 1
This is based on an interview question. I ask for a drawing of logic gates but since this is stackoverflow I'll accept any coding language. Bonus points for a hardware implementation (verilog etc).
Part a (easy): First input is the MSB.
Part b (a little harder): First input is the LSB.
Part c (difficult): Which one is faster and smaller, (a) or (b)? (Not theoretically in the Big-O sense, but practically faster/smaller.) Now take the slower/bigger one and make it as fast/small as the faster/smaller one.

There's a fairly well-known trick for determining whether a number is a multiple of 11, by alternately adding and subtracting its decimal digits. If the number you get at the end is a multiple of 11, then the number you started out with is also a multiple of 11:
47278 4 - 7 + 2 - 7 + 8 = 0, multiple of 11 (47278 = 11 * 4298)
52214 5 - 2 + 2 - 1 + 4 = 8, not multiple of 11 (52214 = 11 * 4746 + 8)
We can apply the same trick to binary numbers. A binary number is a multiple of 3 if and only if the alternating sum of its bits is also a multiple of 3:
4 = 100 1 - 0 + 0 = 1, not multiple of 3
6 = 110 1 - 1 + 0 = 0, multiple of 3
78 = 1001110 1 - 0 + 0 - 1 + 1 - 1 + 0 = 0, multiple of 3
109 = 1101101 1 - 1 + 0 - 1 + 1 - 0 + 1 = 1, not multiple of 3
It makes no difference whether you start with the MSB or the LSB, so the following Python function works equally well in both cases. It takes an iterator that returns the bits one at a time. multiplier alternates between 1 and 2 instead of 1 and -1 to avoid taking the modulo of a negative number.
def divisibleBy3(iterator):
multiplier = 1
accumulator = 0
for bit in iterator:
accumulator = (accumulator + bit * multiplier) % 3
multiplier = 3 - multiplier
return accumulator == 0

Here... something new... how to check if a binary number of any length (even thousands of digits) is divisible by 3.
-->((0))<---1--->()<---0--->(1) ASCII representation of graph
From the picture.
You start in the double circle.
When you get a one or a zero, if the digit is inside the circle, then you stay in that circle. However if the digit is on a line, then you travel across the line.
Repeat step two until all digits are comsumed.
If you finally end up in the double circle then the binary number is divisible by 3.
You can also use this for generating numbers divisible by 3. And I wouldn't image it would be hard to convert this into a circuit.
1 example using the graph...
11000000000001011111111111101 is divisible by 3 (ends up in the double circle again)
Try it for yourself.
You can also do similar tricks for performing MOD 10, for when converting binary numbers into base 10 numbers. (10 circles, each doubled circled and represent the values 0 to 9 resulting from the modulo)
EDIT: This is for digits running left to right, it's not hard to modify the finite state machine to accept the reverse language though.
NOTE: In the ASCII representation of the graph () denotes a single circle and (()) denotes a double circle. In finite state machines these are called states, and the double circle is the accept state (the state that means its eventually divisible by 3)

Heh
State table for LSB:
S I S' O
0 0 0 1
0 1 1 0
1 0 2 0
1 1 0 1
2 0 1 0
2 1 2 0
Explanation: 0 is divisible by three. 0 << 1 + 0 = 0. Repeat using S = (S << 1 + I) % 3 and O = 1 if S == 0.
State table for MSB:
S I S' O
0 0 0 1
0 1 2 0
1 0 1 0
1 1 0 1
2 0 2 0
2 1 1 0
Explanation: 0 is divisible by three. 0 >> 1 + 0 = 0. Repeat using S = (S >> 1 + I) % 3 and O = 1 if S == 0.
S' is different from above, but O works the same, since S' is 0 for the same cases (00 and 11). Since O is the same in both cases, O_LSB = O_MSB, so to make MSB as short as LSB, or vice-versa, just use the shortest of both.

Here is an simple way to do it by hand.
Since 1 = 22 mod 3, we get 1 = 22n mod 3 for every positive integer.
Furthermore 2 = 22n+1 mod 3. Hence one can determine if an integer is divisible by 3 by counting the 1 bits at odd bit positions, multiply this number by 2, add the number of 1-bits at even bit posistions add them to the result and check if the result is divisible by 3.
Example: 5710=1110012.
There are 2 bits at odd positions, and 2 bits at even positions. 2*2 + 2 = 6 is divisible by 3. Hence 57 is divisible by 3.
Here is also a thought towards solving question c). If one inverts the bit order of a binary integer then all the bits remain at even/odd positions or all bits change. Hence inverting the order of the bits of an integer n results is an integer that is divisible by 3 if and only if n is divisible by 3. Hence any solution for question a) works without changes for question b) and vice versa. Hmm, maybe this could help to figure out which approach is faster...

You need to do all calculations using arithmetic modulo 3. This is the way
MSB:
number=0
while(!eof)
n=input()
number=(number *2 + n) mod 3
if(number == 0)
print divisible
LSB:
number = 0;
multiplier = 1;
while(!eof)
n=input()
number = (number + multiplier * n) mod 3
multiplier = (multiplier * 2) mod 3
if(number == 0)
print divisible
This is general idea...
Now, your part is to understand why this is correct.
And yes, do homework yourself ;)

The idea is that the number can grow arbitrarily long, which means you can't use mod 3 here, since your number will grow beyond the capacity of your integer class.
The idea is to notice what happens to the number. If you're adding bits to the right, what you're actually doing is shifting left one bit and adding the new bit.
Shift-left is the same as multiplying by 2, and adding the new bit is either adding 0 or 1. Assuming we started from 0, we can do this recursively based on the modulo-3 of the last number.
last | input || next | example
------------------------------------
0 | 0 || 0 | 0 * 2 + 0 = 0
0 | 1 || 1 | 0 * 2 + 1 = 1
1 | 0 || 2 | 1 * 2 + 0 = 2
1 | 1 || 0 | 1 * 2 + 1 = 0 (= 3 mod 3)
2 | 0 || 1 | 2 * 2 + 0 = 1 (= 4 mod 3)
2 | 1 || 2 | 2 * 2 + 1 = 2 (= 5 mod 3)
Now let's see what happens when you add a bit to the left. First, notice that:
22n mod 3 = 1
and
22n+1 mod 3 = 2
So now we have to either add 1 or 2 to the mod based on if the current iteration is odd or even.
last | n is even? | input || next | example
-------------------------------------------
d/c | don't care | 0 || last | last + 0*2^n = last
0 | yes | 1 || 0 | 0 + 1*2^n = 1 (= 2^n mod 3)
0 | no | 1 || 0 | 0 + 1*2^n = 2 (= 2^n mod 3)
1 | yes | 1 || 0 | 1 + 1*2^n = 2
1 | no | 1 || 0 | 1 + 1*2^n = 0 (= 3 mod 3)
1 | yes | 1 || 0 | 2 + 1*2^n = 0
1 | no | 1 || 0 | 2 + 1*2^n = 1

input "0": (0) output 1
inputs "1,0,0": (4) output 0
inputs "1,1,0,0": (6) output 1
shouldn't this last input be 12, or am i misunderstanding the question?

Actually the LSB method would actually make this easier. In C:
MSB method:
/*
Returns 1 if divisble by 3, otherwise 0
Note: It is assumed 'input' format is valid
*/
int is_divisible_by_3_msb(char *input) {
unsigned value = 0;
char *p = input;
if (*p == '1') {
value &= 1;
}
p++;
while (*p) {
if (*p != ',') {
value <<= 1;
if (*p == '1') {
ret &= 1;
}
}
p++;
}
return (value % 3 == 0) ? 1 : 0;
}
LSB method:
/*
Returns 1 if divisble by 3, otherwise 0
Note: It is assumed 'input' format is valid
*/
int is_divisible_by_3_lsb(char *input) {
unsigned value = 0;
unsigned mask = 1;
char *p = input;
while (*p) {
if (*p != ',') {
if (*p == '1') {
value &= mask;
}
mask <<= 1;
}
p++;
}
return (value % 3 == 0) ? 1 : 0;
}
Personally I have a hard time believing one of these will be significantly different to the other.

I think Nathan Fellman is on the right track for part a and b (except b needs an extra piece of state: you need to keep track of if your digit position is odd or even).
I think the trick for part C is negating the last value at each step. I.e. 0 goes to 0, 1 goes to 2 and 2 goes to 1.

A number is divisible by 3 if the sum of it's digits is divisible by 3.
So you can add the digits and get the sum:
if the sum is greater or equal to 10 use the same method
if it's 3, 6, 9 then it is divisible
if the sum is different than 3, 6, 9 then it's not divisible

Related

Time complexity of nested for loop inside while loop

If there is a nested for loop inside while loop like this:
while(condition)
for(i=0; i<size; i++)
the size in the for loop is increasing every time the for loop is being executed, starting at 1,2,...,n-1
and the while loop runs n-1 times.
That means that the time complexity is O(n^3)?
If by every time the for loop is being executed you mean every time the while(condition) triggers a new run of the for loop, then the time complexity is .
That is, if you increment a counter inside the inner for loop, it will be incremented = n choose 2 times. But because constant factors and lower order terms are omitted in big O notation, we can just write .
For illustration, consider this Python 2.7 implementation (I converted the outer while loop + size increment into a for loop):
n = 10
counter = 0
for size in range(1, n):
for i in range(0, size):
counter += 1
print i,
print
print
print "counter =", counter
print "n choose 2 =", (n * (n - 1)) / 2
Output:
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
counter = 45
n choose 2 = 45
Try running it with different values of n to see that the formula holds true.

Ways to write a number as a sum

I want to write for example number 10 all the possible ways as a sum of units 3, 4, ..., n-1 (not 2)
for example i can write 10 as
10=10(units)
10=7 + 1*3 or
10=4 + 2*3 or
10=3 + 1*3 + 1*4 or
10=2 + 2*4 or ....
I dont care about the number of combinations!
I want the combinations!!! I mean an algoithm to output like this
un 3 4 5 6 7 8 9 10
-------------------
10 0 0 0 0 0 0 0 0
07 1 0 0 0 0 0 0 0
04 2 0 0 0 0 0 0 0
03 1 1 0 0 0 0 0 0
02 0 2 0 0 0 0 0 0 etc
any response is welcomed!!!
start with zero
try to add the largest possible number
store the result, if you arrive at the target sum
else if you ended with less than the target sum, go to (2)
else (if you ended with more than the target sum)
undo the last adding step, try to add one less instead. If you don't have any more smaller numbers to try, undo one more addition in past
if you run out of all possible additions, you already found all combinations and can exit.
Example:
target = 10
0
0 + 9 -> not there yet
0 + 9 + 9 -> too much, try something less
0 + 9 + 8 -> too much, try less
...
...
...
0 + 9 + 3 -> too much, cant try any less
0 + 8 -> not there yet
0 + 8 + 8 -> too much
...
...
...
0 + 8 + 3 -> too much, cant try any less
0 + 7 -> not there yet
0 + 7 + 7 -> too much
0 + 7 + 6 -> too much
...
...
...
0 + 7 + 3 -> thats it! save!
0 + 6 -> not yet
0 + 6 + 6 -> too much...
I hope you get the idea... :)
It will be much much faster, than trying all the possible combinations and selecting only the ones that sum to 10. This approach is called backtracking (https://en.wikipedia.org/wiki/Backtracking), because you try to go in some direction (adding the largest number), but when you fail (sum is too big), you track your progress back and then try something different.
You can then speed it up by trying the possibilities in more clever way (0 + 7 + 7 is too much by 4, so don't even try 0 + 7 + 6, but skip straight to 0 + 7 + 3).

Difference in Ada remainder operators?

So, I know that Ada offers two remainder operators, rem and mod, but what exactly is the difference between them? I was able to find this, but I'm not sure I'm fully grasping the difference.
There's no difference between A mod B and A rem B if A is nonnegative and B is positive. If A is negative and B is positive, mod gives you the true mathematical modulo operation; thus, for example, if B is 5, here are the results of A mod 5 and A rem 5 for values of A:
A = -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8
A mod 5 = 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3
A rem 5 = 0 -4 -3 -2 -1 0 -4 -3 -2 -1 0 1 2 3 4 0 1 2 3
Note the pattern in the A mod 5 results.
rem corresponds to the way the % operator works in C-style languages (but not Python or Ruby, apparently). It may be faster on some processors. If you have to deal with negative values for A, my hunch is that mod is much more likely to be useful, but there may be some uses for rem also. I don't think there's much use at all for mod or rem with a negative right-hand operand, so I wouldn't worry too much about the definition.
See also http://en.wikipedia.org/wiki/Modulo_operation.
According to the LRM, the difference is which operand's sign is associated with the result.
Integer division and remainder are defined by the relation
A = (A/B)*B + (A rem B)
where (A rem B) has the sign of A and an absolute value less than the absolute value of B. Integer division satisfies the identity
(-A)/B = -(A/B) = A/(-B)
The result of the modulus operation is such that (A mod B) has the sign of B and an absolute value less than the absolute value of B; in addition, for some integer value N, this result must satisfy the relation
A = B*N + (A mod B)

Generating certain sequence of numbers with defined ranges

How can I use a collection of nested for loops (or any other type) to produce a sequence like this with these variables:
length is how many digts to go to
max is the maximum number
min is the minimum number
Lets say for this case:
length = 2
max = 3
min = 1
it would produce:
11
12
13
21
22
23
31
32
33
This works "ok" for only length = 1, but not really, since I still have annoying 0's at the start
For i = 1 To length
For ii = 0 To i
For iii = 1 To 5
Console.WriteLine(Str(ii) + Str(iii))
Next
Next
Next
As this looks like a homework problem, I am going to attempt to help you think through this problem without actually giving you the answer in code.
Let's think through this problem...
You have the range 1-3. So your first sequence is easy:
1, 2, 3
Now you want to produce a sequence from 11 to 13. What's the change, or difference, between 1 through 3 and 11 through 13? The answer is you've added 10.
The same is true for 21 through 23 - you've added 10 again.
So, what you want to do is iterate from 1 through 3.
Then, iterate from 1 through 3 this time adding 10.
Then, iterate from 1 through 3 this time adding 20.
Thinking about this, you are essentially doing this:
1
2
3
10 + 1
10 + 2
10 + 3
10 + 10 + 1
10 + 10 + 2
10 + 10 + 3
etc
Or, you could also think about it like this:
(0 * 10) + 1
(0 * 10) + 2
(0 * 10) + 3
(1 * 10) + 1
(1 * 10) + 2
(1 * 10) + 3
(2 * 10) + 1
(2 * 10) + 2
(2 * 10) + 3
etc
Can you see a pattern forming?

Extracting data from binary data stream in nsdata

I'm new to objective c at the moment and trying to decode a data stream that I'm getting as an NSdata object..
the data is 8 bytes long, eg:
1 2 3 4
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| code1 |code2 | code3 | code4 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
5 6 7 8
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
code5 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
From the nsdata array, how could i easily put out the different codes, considering that code3 doesnt sit on a byte boundary?
I've tried the likes of this:
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
however cannot make it work properly with the different boundaries.. Apologies if this seems a bit vague, can confirm details if need be
What you're doing looks fine - what's the issue? Are you able to get the data in to your byteData pointer? If so, then it's no different between objective-c or C or anything else (and NSData isn't really a good tag then) - you just need to access your bytes bitwise.
This could be achieved by creating a structure with bitfield definitions like this (pseudocode, google bitfield)
struct
{
char byte1;
char a3bitfield : 3;
char a5bitfield : 5;
char byte3;
}
Or by using bitmasks and or by using shifts.
Edit in response to comment:
This shows how to do the shifting
First issue you're going to have is that you are showing your bits from left to right, which on little-endian systems is not accurate, you need to think about the bits as being:
7 6 5 4 3 2 1 0
Instead of
0 1 2 3 4 5 6 7
Otherwise you will never understand how the masking and shifting directions will work.
So assuming that you have bytes broken out, as you seem to, and you know what byte you're operating on, byte x :
7 6 5 4 3 2 1 0
[5 bits a][3 bits b]
Where a and b are messages you care about, the way to get these "alone" would be:
char onlya = ((x & 11111000b) >> 3);
Which means, I want tto use those top 5 bits of a, and discard the lowest 3 bits, and then shift everything 3 bits to the right to compensate. If you started with:
AAAAABBB where A is data from a and B is data from B that you don't care about, the "x & 11111000b" will result in:
AAAAA000
And the subsequent >> 3 will result in:
000AAAAA
Where the A's come from right shifting, introducing 0's where the gaps were and discarding the 0's on the right.
So to get B alone in this case, you'd only have to do:
char onlyb = (x & 00000111b);
No shift necessary.
If you're working across bit boundaries with 2 bytes N and M such as:
N M
7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
X X X X A A A A A A A X X X X X
You would do:
char merged = 0;
merged |= (N & 00001111b) << 3;
merged |= (M & 11100000b) >> 5;
I'm masking out to only get A from N and M, and then I'm shifting to the RESULTING LOCATION. So that when I'm done with these 3 steps in order, the result on merged will be:
merged = 0 gives:
0 0 0 0 0 0 0 0
First merged |= gives:
0 N N N N 0 0 0
Second merged |= gives:
0 N N N N M M M
At this point, you act on your data as you normally would (cast to int or whatever)
And like I said, the alternative is bitfields