+ 13
[assignment] Check if a binary number is devisible by 7 with following rules
a binary number is devisible by 7,if it has exactly 3*n 1. For each 1 calculate modpos = position mod 3. So if a 1 is at position 4, the modpos is 1. modpos0 is the count of all 1 with modpos = 0 modpos1 is the count of all 1 with modpos = 1 modpos2 is the count of all 1 with modpos = 2. if modpos0 == modpos1 == modpos2 the binary is devisible by 7. eg b111111 1 at position 1,2,3,4,5,6 which makes modpos 1,2,0,1,2,0 modpos0 == modpos1 == modpos2 = 2 Edit: you will not find all numbers. b111111 = 63 is devisible by 7.
12 Respostas
+ 11
Hi Oma !
I think my code follows your rules, but it misses many numbers. When the conditions are met, the number is actually divisible by 7, but not all of the multiples of 7 will match the conditions. Or am I wrong ?
https://code.sololearn.com/c0qHtxHoItGx/#py
+ 8
CĂ©pagrave yes u are right. It is a => constraint but not <=>.
+ 6
2 additionnal ways to do it
https://code.sololearn.com/cC094JcrxnXX/?ref=app
+ 5
https://code.sololearn.com/cC094JcrxnXX/?ref=app
+ 5
here is my quirk solution using regex. to be precise for automate or Turing machine. I did not think that it is so cumbersome.
https://code.sololearn.com/cUZ9tEhA13OA/?ref=app
+ 4
bool div7(unsigned n){
unsigned mods[3] = {0};
while(n){
for(int i = 0; i < 3; ++i)
mods[i] += (n & (1 << i)) >> i;
n >>= 3;
}
return mods[0] == mods[1] && mods[0] == mods[2];
}
+ 4
very nice the algorithm
+ 3
yuri awfully inefficient but really cool
0
This Works! It's Faster!
A binary number is divisible by 7, if you group the digits into sets of 3 each, sum all grouped digits and check if this sum is divisible by 7.
(use zeroes to fill in the leading digit gaps, as is obvious)