473,320 Members | 2,088 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

division by 7 without using division operator

Last month I appeared for an interview with EA sports and they asked
me this question.

How would you divide a number by 7 without using division operator ?

I did by doing a subtraction and keeping a counter that kept a tab on
how many times I subtracted.

Later, the EA sport guy told me that of course there are can be better
technique by using bit operator.

Since 7 has a binary representation 111, my guess is that a left shift
operation of 3 bits should give the answer, but I couldn't get it to
work.

Any comments ?

Feb 1 '07
94 11364
mi****@gmail.com said:
On Feb 2, 7:03 am, Richard Heathfield <r...@see.sig.invalidwrote:
>>
If I'm hiring, I want someone who knows the language. Something
wrong with that?

Presumably you test something that is related to understanding
algorithms and data structures as well.
Yes.
Now what if the intersection of candidates that get the assert thingy
right with those that have suitable knowledge of algorithms and data
structures is empty, and both set differences are non-empty. Whom do you
pick?
If no suitable candidate is forthcoming, what can you do? Either you look
for more candidates, or you make do with an unsuitable candidate, or you
leave the post vacant.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 2 '07 #51
>>>>"RH" == Richard Heathfield <rj*@see.sig.invalidwrites:

RHmi****@gmail.com said:
>Now what if the intersection of candidates that get the assert
thingy right with those that have suitable knowledge of
algorithms and data structures is empty, and both set
differences are non-empty. Whom do you pick?
RHIf no suitable candidate is forthcoming, what can you do?
RHEither you look for more candidates, or you make do with an
RHunsuitable candidate, or you leave the post vacant.

Or you consider which of the candidates can learn what you need them
to learn most easily -- the *degree* of suitability. The assert thing
is a small detail, that I myself didn't know because I've never run
into it. But Mr Heathfield's entire exercise will demonstrate whether
the candidate understands and values conforming code, and that's a lot
more important than whether the candidate knows the minutiae of the
Standard as regards functions he may never use.

Of course, quite a bit of this can be dealt with by asking for code
samples in advance.

Charlton


--
Charlton Wilbur
cw*****@chromatico.net
Feb 2 '07 #52
In article <pa****************************@this.address>,
Duncan Muirhead <no***@this.addresswrote:
>If n >= 0 we can compute q>=0 and 0<=r<8 with n = 8*q + r using
>>and &. So n = 7*q + q+r hence n/7 = q + (q+r)/7. For n>7
we have q+r < n, so we can iterate.
Yes, that should work. Let's turn that into C code:

int divide_by_7(int x)
/*
precondition: 0 <= x
returns x / 7
*/
{
int q = 0, r = x + 1; /* invariant: x == 7 * q + r - 1 and 1 <= r */
while (8 <= r)
{
/* x == 7 * q + r - 1 and 8 <= r */
int u = r / 8, v = r % 8; /* use bit twiddling instead, if desired */
/* x == 7 * q + (8 * u + v) - 1
== 7 * (q + u) + (u + v) - 1 and 1 <= u and 0 <= v */
q += u;
r = u + v;
/* x == 7 * q + r - 1 and 1 <= r */
}
/* x == 7 * q + r - 1 and 0 <= r - 1 < 7 */
return q;
}

Cheers,
Ike
Feb 2 '07 #53
Charlton Wilbur said:
>>>>>"RH" == Richard Heathfield <rj*@see.sig.invalidwrites:
<snip>
>
RHIf no suitable candidate is forthcoming, what can you do?
RHEither you look for more candidates, or you make do with an
RHunsuitable candidate, or you leave the post vacant.

Or you consider which of the candidates can learn what you need them
to learn most easily -- the *degree* of suitability.
Yes. If you're prepared to take an unsuitable candidate, obviously you'll
want to take the /least/ unsuitable candidate. :-)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 3 '07 #54
Richard Heathfield wrote:
Charlton Wilbur said:
>>Richard Heathfield <rj*@see.sig.invalidwrites:
<snip>
>>
>>If no suitable candidate is forthcoming, what can you do?
Either you look for more candidates, or you make do with an
unsuitable candidate, or you leave the post vacant.

Or you consider which of the candidates can learn what you need
them to learn most easily -- the *degree* of suitability.

Yes. If you're prepared to take an unsuitable candidate, obviously
you'll want to take the /least/ unsuitable candidate. :-)
Which brings up a very common C task - write a compare function.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 3 '07 #55

"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:q7******************************@bt.com...
I'd expect the successful candidate to be drawn from those who spotted it,
yes.
>Cmon.

Hmm? If I'm hiring, I want someone who knows the language. Something wrong
with that?
>If you state generally "what is wrong with this code?" you're not going
to
get the prime answer as one focusing on the most subtle element in the
first place.

No, but the people I'd want to hire would at least mention it, possibly
with
a little non-spoonfeedy prompting, like Ben did (although if I were
hiring,
I wouldn't bother interviewing Ben - I'd just show him his reserved
parking
spot and ask when he planned to start using it).
I do think its taking it a bit too far.
I remember getting an interview question which showed this code:

enum E
{
X,
Y,
};
(and more ofcourse)

The question wasnt about that, but I happened to know that the last comma is
actually allowed so I decided to mention this. And there we went, the
interviewer was a C coder with 20 years of cranking out working code
experience under his belt and he kept insisting that this is not allowed.
You know how programmers can be :) I bet I'll get the same type of situation
if I'd tell about the assert.
Hmm might be interesting test, I work in a place with 15 or so C programmers
from beginner to very experienced. I wonder how many will spot the "error"
Feb 4 '07 #56

"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:g5******************************@bt.com...
Richard Bos said:
>ri*****@cogsci.ed.ac.uk (Richard Tobin) wrote:
>>In article <eK******************************@bt.com>,
Richard Heathfield <rj*@see.sig.invalidwrote:

Most were obvious, of course, but there was a subtlety in there that I
would expect only an expert to spot.

Go on, tell us. I assume it's that assert(pointer) is not allowed
(but works on all known systems).

If it is, it's a wrong gotcha.

No, it isn't.
well, using assert for things that can happen in production code too is also
not correct
Feb 4 '07 #57
Serve Laurijssen wrote:
"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:q7******************************@bt.com...
>>I'd expect the successful candidate to be drawn from those who spotted it,
yes.

>>>Cmon.

Hmm? If I'm hiring, I want someone who knows the language. Something wrong
with that?

>>>If you state generally "what is wrong with this code?" you're not going
to
get the prime answer as one focusing on the most subtle element in the
first place.

No, but the people I'd want to hire would at least mention it, possibly
with
a little non-spoonfeedy prompting, like Ben did (although if I were
hiring,
I wouldn't bother interviewing Ben - I'd just show him his reserved
parking
spot and ask when he planned to start using it).


I do think its taking it a bit too far.
I remember getting an interview question which showed this code:

enum E
{
X,
Y,
};
(and more ofcourse)

The question wasnt about that, but I happened to know that the last comma is
actually allowed so I decided to mention this. And there we went, the
interviewer was a C coder with 20 years of cranking out working code
experience under his belt and he kept insisting that this is not allowed.
You know how programmers can be :)
I believe that he's right, not allowed in C89 but allowed in C99. My
authorative source for this is google and gcc ;-)
http://groups.google.com/group/comp....940657c313d97a

Boa
[snip]
Feb 4 '07 #58

"boa sema" <bo*****@gmail.comwrote in message
news:ot********************@telenor.com...
Serve Laurijssen wrote:
>>>>If you state generally "what is wrong with this code?" you're not going
to
get the prime answer as one focusing on the most subtle element in the
first place.

No, but the people I'd want to hire would at least mention it, possibly
with
a little non-spoonfeedy prompting, like Ben did (although if I were
hiring,
I wouldn't bother interviewing Ben - I'd just show him his reserved
parking
spot and ask when he planned to start using it).


I do think its taking it a bit too far.
I remember getting an interview question which showed this code:

enum E
{
X,
Y,
};
(and more ofcourse)

The question wasnt about that, but I happened to know that the last comma
is actually allowed so I decided to mention this. And there we went, the
interviewer was a C coder with 20 years of cranking out working code
experience under his belt and he kept insisting that this is not allowed.
You know how programmers can be :)

I believe that he's right, not allowed in C89 but allowed in C99. My
authorative source for this is google and gcc ;-)
http://groups.google.com/group/comp....940657c313d97a
Yes so it is allowed....but here we go already. standard this year standard
that year and all about stuff that doesnt make you a better C coder. Like
with the assert(p)
Feb 4 '07 #59
Serve Laurijssen said:

<snip>
well, using assert for things that can happen in production code too is
also not correct
Right; as I have said dozens of times in this newsgroup, assert is for
validating code, not data.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 4 '07 #60
Richard Heathfield wrote:
Serve Laurijssen said:

<snip>

>>well, using assert for things that can happen in production code too is
also not correct


Right; as I have said dozens of times in this newsgroup, assert is for
validating code, not data.
assert() is for validating code & data, but not input data.

Boa
Feb 4 '07 #61
boa sema said:
Richard Heathfield wrote:
>Serve Laurijssen said:

<snip>

>>>well, using assert for things that can happen in production code too is
also not correct


Right; as I have said dozens of times in this newsgroup, assert is for
validating code, not data.

assert() is for validating code & data, but not input data.
What kind of data did you have in mind, other than input data?

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 4 '07 #62
Richard Heathfield wrote:
boa sema said:

>>Richard Heathfield wrote:
>>>Serve Laurijssen said:

<snip>

well, using assert for things that can happen in production code too is
also not correct
Right; as I have said dozens of times in this newsgroup, assert is for
validating code, not data.

assert() is for validating code & data, but not input data.


What kind of data did you have in mind, other than input data?
How about function arguments?

One may of course argue that the calling *code* is broken if the data is
broken.

Boa
Feb 4 '07 #63
boa sema said:
Richard Heathfield wrote:
>boa sema said:
<snip>
>>>
assert() is for validating code & data, but not input data.

What kind of data did you have in mind, other than input data?
How about function arguments?
That sure sounds like input data to me.
One may of course argue that the calling *code* is broken if the data is
broken.
Quite so.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 4 '07 #64
In article <eq**********@news2.zwoll1.ov.home.nl>,
Serve Laurijssen <se*@n.tkwrote:
>well, using assert for things that can happen in production code too is also
not correct
If you had said "... in correct production code ...", I would have
agreed. But I don't see any point removing assert()s from production
code (unless they're expensive to compute), because even in production
code it's generally better to abort with a useful message if there
turns out to be a bug in the code. No doubt there are exceptions.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 4 '07 #65

"Richard Tobin" <ri*****@cogsci.ed.ac.ukwrote in message
news:eq**********@pc-news.cogsci.ed.ac.uk...
In article <eq**********@news2.zwoll1.ov.home.nl>,
Serve Laurijssen <se*@n.tkwrote:
>>well, using assert for things that can happen in production code too is
also
not correct

If you had said "... in correct production code ...", I would have
agreed. But I don't see any point removing assert()s from production
code (unless they're expensive to compute), because even in production
code it's generally better to abort with a useful message if there
turns out to be a bug in the code. No doubt there are exceptions.
Well assert is not the way to gio then. You can add an assert like debug
facility that can be turned on/off by the user
Feb 4 '07 #66
"Serve Laurijssen" <se*@n.tkwrites:
[...]
Yes so it is allowed....but here we go already. standard this year standard
that year and all about stuff that doesnt make you a better C coder. Like
with the assert(p)
I don't understand your point. How does understanding what's defined
in the C90 and C99 standards not make you a better C coder?

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 4 '07 #67
In article <eq**********@news2.zwoll1.ov.home.nl>,
Serve Laurijssen <se*@n.tkwrote:
>If you had said "... in correct production code ...", I would have
agreed. But I don't see any point removing assert()s from production
code (unless they're expensive to compute), because even in production
code it's generally better to abort with a useful message if there
turns out to be a bug in the code. No doubt there are exceptions.
>Well assert is not the way to gio then. You can add an assert like debug
facility that can be turned on/off by the user
If there's a bug in my code, I probably don't want the user to be able
to disable its detection.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 4 '07 #68
"Serve Laurijssen" <se*@n.tkwrites:
"Richard Tobin" <ri*****@cogsci.ed.ac.ukwrote in message
news:eq**********@pc-news.cogsci.ed.ac.uk...
In article <eq**********@news2.zwoll1.ov.home.nl>,
Serve Laurijssen <se*@n.tkwrote:
>well, using assert for things that can happen in production code too is
also
not correct
If you had said "... in correct production code ...", I would have
agreed. But I don't see any point removing assert()s from production
code (unless they're expensive to compute), because even in production
code it's generally better to abort with a useful message if there
turns out to be a bug in the code. No doubt there are exceptions.

Well assert is not the way to gio then. You can add an assert like debug
facility that can be turned on/off by the user
The point, I think, is that an assert() that will be triggered *only*
if there's a bug in the code is acceptable, even in production code.

For example suppose you have a function that's intended only to accept
an argument value in the range 1..10. You might write it like this:

void func(int n)
{
assert(n >= 1 && n <= 10);
/* ... */
}

Assuming that func() is invoked by code in your application, that you
control, and never with some user-defined input value. Then a call
func(11) is a genuine bug in the program, not a data error.

If there's any combination of user data that can cause the assert() to
be triggered, then a different mechanism should be used, even if the
program just prints an error message and dies.

Now if you're able to recover from the error (perhaps by saving any
user data), that's even better, but your efforts as a developer are
probably better spent fixing the bug.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 4 '07 #69
On Feb 4, 10:53 am, rich...@cogsci.ed.ac.uk (Richard Tobin) wrote:
But I don't see any point removing assert()s from production
code (unless they're expensive to compute), because even in production
code it's generally better to abort with a useful message if there
turns out to be a bug in the code. No doubt there are exceptions.
I can offer that console video game DVDs ship with all the asserts
removed.

After all, there's no going back and fixing it after that. (At least
with the PS2/Xbox generation.)

-Beej

Feb 5 '07 #70
ri*****@cogsci.ed.ac.uk (Richard Tobin) wrote:
In article <eq**********@news2.zwoll1.ov.home.nl>,
Serve Laurijssen <se*@n.tkwrote:
If you had said "... in correct production code ...", I would have
agreed. But I don't see any point removing assert()s from production
code (unless they're expensive to compute), because even in production
code it's generally better to abort with a useful message if there
turns out to be a bug in the code. No doubt there are exceptions.
Well assert is not the way to gio then. You can add an assert like debug
facility that can be turned on/off by the user

If there's a bug in my code, I probably don't want the user to be able
to disable its detection.
True, but neither do I want to present him with a cryptic, tenth-of-a-
second flash of (to him) unintelligible console text and an immediate
return to his desktop. So rather than assert(), my preference is for a
function which can put a quotable, repeatable error message on his
screen and keep it there until he's finished phoning me.

Richard
Feb 5 '07 #71
In article <45*****************@news.xs4all.nl>,
Richard Bos <rl*@hoekstra-uitgeverij.nlwrote:
>True, but neither do I want to present him with a cryptic, tenth-of-a-
second flash
??? Why do your assert messages only last a tenth of a second?
>of (to him) unintelligible console text and an immediate
return to his desktop.
Ah. I don't use one of those desktop thingies. Most of my programs
have no graphical interface. But I don't see any excuse for systems
where output to stderr vanishes immediately.
>So rather than assert(), my preference is for a
function which can put a quotable, repeatable error message on his
screen and keep it there until he's finished phoning me.
Assert error messages may be cryptic, but they come with a file and
line number. I don't see why they would not be repeatable.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 5 '07 #72
ri*****@cogsci.ed.ac.uk (Richard Tobin) wrote:
In article <45*****************@news.xs4all.nl>,
Richard Bos <rl*@hoekstra-uitgeverij.nlwrote:
True, but neither do I want to present him with a cryptic, tenth-of-a-
second flash

??? Why do your assert messages only last a tenth of a second?
of (to him) unintelligible console text and an immediate
return to his desktop.

Ah. I don't use one of those desktop thingies.
_So_ nice for you.

Most production peons wouldn't know which end of a CLI was which.
So rather than assert(), my preference is for a
function which can put a quotable, repeatable error message on his
screen and keep it there until he's finished phoning me.

Assert error messages may be cryptic, but they come with a file and
line number. I don't see why they would not be repeatable.
Your species of luser much be about twelve thousand years futher along
the evolutionary ladder than mine. Congratulations.

I wasn't talking about assert() messages that _I_ see, but about those
that the average, Windows-only, can't-remember-any-numbers, Word-is-
complicated data entry employee sees.

Richard
Feb 5 '07 #73

"Keith Thompson" <ks***@mib.orgwrote in message
news:ln************@nuthaus.mib.org...
"Serve Laurijssen" <se*@n.tkwrites:
[...]
>Yes so it is allowed....but here we go already. standard this year
standard
that year and all about stuff that doesnt make you a better C coder. Like
with the assert(p)

I don't understand your point. How does understanding what's defined
in the C90 and C99 standards not make you a better C coder?
I'm talking about the assert and enum comma example. Knowing those rules
doesnt help one at all to become a better C coder.
Feb 5 '07 #74
Richard Tobin wrote:
In article <eq**********@news2.zwoll1.ov.home.nl>,
Serve Laurijssen <se*@n.tkwrote:
>>well, using assert for things that can happen in production code too is also
not correct

If you had said "... in correct production code ...", I would have
agreed. But I don't see any point removing assert()s from production
code (unless they're expensive to compute), because even in production
code it's generally better to abort with a useful message if there
turns out to be a bug in the code. No doubt there are exceptions.

-- Richard
I have found on more than one occasion developers leaving in assertions in
production code on hardware (network equipment) for serious "should not
happen" cases. When it does happen - you submit a bug and they follow up.
What are people's opinions on this?
Feb 5 '07 #75
"Serve Laurijssen" <se*@n.tkwrites:
"Keith Thompson" <ks***@mib.orgwrote in message
news:ln************@nuthaus.mib.org...
"Serve Laurijssen" <se*@n.tkwrites:
[...]
Yes so it is allowed....but here we go already. standard this year
standard
that year and all about stuff that doesnt make you a better C coder. Like
with the assert(p)
I don't understand your point. How does understanding what's defined
in the C90 and C99 standards not make you a better C coder?

I'm talking about the assert and enum comma example. Knowing those rules
doesnt help one at all to become a better C coder.
Of course it does. I can't imagine why you would think it doesn't.
For example, coding includes maintaining existing code, some of which
might depend on those rules you're trying to ignore.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 5 '07 #76
On 1 fév, 05:03, krypto.wiz...@gmail.com wrote:
Last month I appeared for an interview with EA sports and they asked
me this question.

How would you divide a number by 7 without using division operator ?
To suceed in these interviews, I fear that you must not be so smart as
to outsmart the person asking the questions. So I suspect the right
answer might have been

number *= 0.142857142857143; // divide by 7

which indeed, in quite a few contexts, is an approriate answer.

Francois Grieu

Feb 5 '07 #77
In article <11*********************@h3g2000cwc.googlegroups.c om"Francois Grieu" <fg****@gmail.comwrites:
....
To suceed in these interviews, I fear that you must not be so smart as
to outsmart the person asking the questions. So I suspect the right
answer might have been

number *= 0.142857142857143; // divide by 7

which indeed, in quite a few contexts, is an approriate answer.
Indeed, it gives the correct answer for all integers from 0 to
2147483647.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Feb 6 '07 #78
"Dik T. Winter" wrote:
"Francois Grieu" <fg****@gmail.comwrites:
...
>To suceed in these interviews, I fear that you must not be so
smart as to outsmart the person asking the questions. So I
suspect the right answer might have been

number *= 0.142857142857143; // divide by 7

which indeed, in quite a few contexts, is an approriate answer.

Indeed, it gives the correct answer for all integers from 0 to
2147483647.
And probably down to -2147483648.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 6 '07 #79
CBFalconer said:
"Dik T. Winter" wrote:
>"Francois Grieu" <fg****@gmail.comwrites:
...
>>To suceed in these interviews, I fear that you must not be so
smart as to outsmart the person asking the questions. So I
suspect the right answer might have been

number *= 0.142857142857143; // divide by 7

which indeed, in quite a few contexts, is an approriate answer.

Indeed, it gives the correct answer for all integers from 0 to
2147483647.

And probably down to -2147483648.
An exercise for those with way too much time on their hands: what is the
smallest-magnitude integer (i.e. regardless of sign) for which it
fails? If this number is negative, what is the smallest *positive*
integer for which it fails?

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 6 '07 #80
Christopher Layne <cl****@com.anodizedwrote:
Richard Tobin wrote:
In article <eq**********@news2.zwoll1.ov.home.nl>,
Serve Laurijssen <se*@n.tkwrote:
>well, using assert for things that can happen in production code too is also
not correct
If you had said "... in correct production code ...", I would have
agreed. But I don't see any point removing assert()s from production
code (unless they're expensive to compute), because even in production
code it's generally better to abort with a useful message if there
turns out to be a bug in the code. No doubt there are exceptions.

I have found on more than one occasion developers leaving in assertions in
production code on hardware (network equipment) for serious "should not
happen" cases. When it does happen - you submit a bug and they follow up.
What are people's opinions on this?
That's different. If it really is not supposed to happen, even if
there's a minor bug in earlier code, a cryptic error message may be
excusable. I'd still advocate putting it up where a normal user of the
program can see it, but if you're writing a hardware driver, it's hard
to see where that is.

Richard
Feb 6 '07 #81
Richard Bos wrote:
>I have found on more than one occasion developers leaving in assertions in
production code on hardware (network equipment) for serious "should not
happen" cases. When it does happen - you submit a bug and they follow up.
What are people's opinions on this?

That's different. If it really is not supposed to happen, even if
there's a minor bug in earlier code, a cryptic error message may be
excusable. I'd still advocate putting it up where a normal user of the
program can see it, but if you're writing a hardware driver, it's hard
to see where that is.

Richard
The cases which have exemplified this were like the following:

1. Failing memory.
2. Failing hardware (signal egregiously out of spec, etc.).
3. Indirect "should not happen"'s which were really "this shouldn't happen if
we had no bug."
Feb 6 '07 #82
Richard Heathfield wrote:
CBFalconer said:
>"Dik T. Winter" wrote:
>>"Francois Grieu" <fg****@gmail.comwrites:
...
To suceed in these interviews, I fear that you must not be so
smart as to outsmart the person asking the questions. So I
suspect the right answer might have been

number *= 0.142857142857143; // divide by 7

which indeed, in quite a few contexts, is an approriate answer.

Indeed, it gives the correct answer for all integers from 0 to
2147483647.

And probably down to -2147483648.

An exercise for those with way too much time on their hands: what
is the smallest-magnitude integer (i.e. regardless of sign) for
which it fails? If this number is negative, what is the smallest
*positive* integer for which it fails?
Without spending too much time on it, the error will be roughly
0.000000000000000143 * N. Equating this expression (abs) to 1.0
should give you the answer.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 6 '07 #83
"Keith Thompson" <ks***@mib.orgwrote in message
news:ln************@nuthaus.mib.org...
Of course it does. I can't imagine why you would think it doesn't.
For example, coding includes maintaining existing code, some of which
might depend on those rules you're trying to ignore.
Well then, might as well let job applicants cite whole pages from the
standard then.
Considering somebody an expert because he knows why assert(p) is wrong is
taking it too far, all he had to do is read comp.lang.c a week :) There's
far worse maintenance problems than assert and enum comma's
Feb 6 '07 #84

"Richard Tobin" <ri*****@cogsci.ed.ac.ukwrote in message
news:eq**********@pc-news.cogsci.ed.ac.uk...
In article <eq**********@news2.zwoll1.ov.home.nl>,
Serve Laurijssen <se*@n.tkwrote:
>>If you had said "... in correct production code ...", I would have
agreed. But I don't see any point removing assert()s from production
code (unless they're expensive to compute), because even in production
code it's generally better to abort with a useful message if there
turns out to be a bug in the code. No doubt there are exceptions.
>>Well assert is not the way to gio then. You can add an assert like debug
facility that can be turned on/off by the user

If there's a bug in my code, I probably don't want the user to be able
to disable its detection.
assert in production code "disables" detection of bugs at users already so
Im not sure if you been keeping up here. Better provide assert like
functionality where at least you and the user have the choice of turning it
on.
Feb 6 '07 #85
On Feb 1, 9:03 am, krypto.wiz...@gmail.com wrote:
Last month I appeared for an interview with EA sports and they asked
me this question.

How would you divide a number by 7 without using division operator ?
quotient = ( value > 3 ) & 0x1FFFF;

The assumption is that of 4 byte integer and signed types. & is to be
used when using signed integers because if the most significant bit of
value was filled right shift will append 1's at the beginning of your
number.
I did by doing a subtraction and keeping a counter that kept a tab on
how many times I subtracted.

Later, the EA sport guy told me that of course there are can be better
technique by using bit operator.

Since 7 has a binary representation 111, my guess is that a left shift
operation of 3 bits should give the answer, but I couldn't get it to
work.
The right shift will work. This technique works only when the divisor
is of the bit pattern 11...1 in other words it has to be 1 less than a
power of 2. 7,15,31 will work.

This technique is used a lot in linux kernel/related system software
to create circular buffers which have number of elements as a power of
2 and then use this technique to wrap around the buffer when index
reaches end (though here remainder calculation is done which is simple
x = x & 0x0003 )
>
Any comments ?
Bit masking techniques take lesser MIPS in general than iteration
based techniques. Loop based techniques also need loop index
variables. But bit masking techniques churn out cryptic code and often
non portable so one must use them with utmost caution.

Feb 6 '07 #86
The fact that compilers can perform this optimization -- and, perhaps
more important, can decide when it is and isn't necessary -- is a good
reason *not* to bother doing this yourself. Just divide by 7; that's
what the "/" operator is for.
/ operator often leads to 32 instructions of shift and add or an
instruction which takes that much time unless you have a multiplier
application to do it. This is the reason many a times it is avoided in
DSP, embedded systems applications and such hacks are needed.

Feb 6 '07 #87
Richard Heathfield wrote:
CBFalconer said:
"Dik T. Winter" wrote:
"Francois Grieu" <fg****@gmail.comwrites:
...
To suceed in these interviews, I fear that you must not be so
smart as to outsmart the person asking the questions. So I
suspect the right answer might have been

number *= 0.142857142857143; // divide by 7

which indeed, in quite a few contexts, is an approriate answer.

Indeed, it gives the correct answer for all integers from 0 to
2147483647.
And probably down to -2147483648.

An exercise for those with way too much time on their hands: what is the
smallest-magnitude integer (i.e. regardless of sign) for which it
fails? If this number is negative, what is the smallest *positive*
integer for which it fails?
It depends on the implementation's precision and the rounding mode.
One possible answer: C90 (but not C99) allows integer division to
round towards negative infinity, so -1 / 7 could be -1, but -1 *
0.142857142857143 is always 0.

Mathematically, 0.142857142857143 is equal to 1.000000000000001 / 7,
so another possible answer is easy to guess and confirm:
100000000000000.

100000000000000 * 0.142857142857143 is 142857142857143
100000000000000 / 7 is 142857142857142.8..., which becomes
142857142857142 because floating point to integer conversions round
towards zero. For any smaller positive number, the exact difference
between the two numbers cannot be greater than 1/7, so when rounding
towards zero, it cannot make a difference. Also, when rounding towards
zero, the sign doesn't matter.

There are other possible answers depending on the representation of
double.

Feb 6 '07 #88
Christopher Layne wrote, On 06/02/07 07:12:
Richard Bos wrote:
>>I have found on more than one occasion developers leaving in assertions in
production code on hardware (network equipment) for serious "should not
happen" cases. When it does happen - you submit a bug and they follow up.
What are people's opinions on this?
That's different. If it really is not supposed to happen, even if
there's a minor bug in earlier code, a cryptic error message may be
excusable. I'd still advocate putting it up where a normal user of the
program can see it, but if you're writing a hardware driver, it's hard
to see where that is.

Richard

The cases which have exemplified this were like the following:

1. Failing memory.
2. Failing hardware (signal egregiously out of spec, etc.).
An assert is not always correct (what if the purpose of the program is
to test the HW?) but I would have no problem with some appropriate form
of "display message and terminate" be it abort or some other appropriate
mechanism, and depending on the program assert may be fine.
3. Indirect "should not happen"'s which were really "this shouldn't happen if
we had no bug."
Again, sometimes "display message and terminate" would be appropriate so
sometimes assert may be OK, but other times you might need to use
something else for the "display message" part or you might want to save
the current state somewhere so an attempt at recovery can be made.

In short, it depends.
--
Flash Gordon
Feb 6 '07 #89

"Christopher Layne" <cl****@com.anodizedwrote in message
news:11************@news-west.n...
Richard Tobin wrote:
>Even more off-topic:

I used a similar trick years ago in Minix, which had no function for
sleeping less than a second. Internally, it slept in units of 1/60
second, and carelessly multiplied the argument to sleep() by 60. By
passing a suitable large number, one could arrange for the overflow to
produce a desired fraction of a second:

This is such an awesomely unportable hack - I love it.

Richard 1, Minix 0.
sometimes programming is fun :)
Feb 6 '07 #90
"quarkLore" <ag*************@gmail.comwrites:
On Feb 1, 9:03 am, krypto.wiz...@gmail.com wrote:
>Last month I appeared for an interview with EA sports and they asked
me this question.

How would you divide a number by 7 without using division operator ?
quotient = ( value > 3 ) & 0x1FFFF;

The assumption is that of 4 byte integer and signed types. & is to be
used when using signed integers because if the most significant bit of
value was filled right shift will append 1's at the beginning of your
number.
C leaves the result of right shifting a signed int up to the
implementation, so you don't know what will happen. If the sign is
extended down, it is probably because it is arithmetically correct on
that implementation, so masking is then the wrong thing to do. If the
shift is not sign-extended, masking won't help so I don't see the
value of it.

I don't think shifting by 3 when the interviewer wanted a divide by 7
would get you the job!

--
Ben.
Feb 6 '07 #91
"Serve Laurijssen" <se*@n.tkwrites:
"Keith Thompson" <ks***@mib.orgwrote in message
news:ln************@nuthaus.mib.org...
Of course it does. I can't imagine why you would think it doesn't.
For example, coding includes maintaining existing code, some of which
might depend on those rules you're trying to ignore.

Well then, might as well let job applicants cite whole pages from the
standard then.
Considering somebody an expert because he knows why assert(p) is wrong is
taking it too far, all he had to do is read comp.lang.c a week :) There's
far worse maintenance problems than assert and enum comma's
Yes, there are, and I never claimed otherwise, nor did I claim that
knowing why assert(p) is wrong makes someone an expert. It is,
however, *part* of being an expert.

Here's what you said upthread:
| I'm talking about the assert and enum comma example. Knowing those rules
| doesnt help one at all to become a better C coder.

That statement was clearly wrong. No one piece of knowledge can make
you an expert, but surely more knowledge is better than less
knowledge. The assert and enum comma examples are relatively minor
points, but they not *completely* insignificant.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 6 '07 #92
"quarkLore" <ag*************@gmail.comwrites:
On Feb 1, 9:03 am, krypto.wiz...@gmail.com wrote:
Last month I appeared for an interview with EA sports and they asked
me this question.

How would you divide a number by 7 without using division operator ?
quotient = ( value > 3 ) & 0x1FFFF;

The assumption is that of 4 byte integer and signed types. & is to be
used when using signed integers because if the most significant bit of
value was filled right shift will append 1's at the beginning of your
number.
So 7 / 7 == 0? Fascinating.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 6 '07 #93
"quarkLore" <ag*************@gmail.comwrites:
The fact that compilers can perform this optimization -- and, perhaps
more important, can decide when it is and isn't necessary -- is a good
reason *not* to bother doing this yourself. Just divide by 7; that's
what the "/" operator is for.
I wrote the above. Please don't snip attribution lines.
/ operator often leads to 32 instructions of shift and add or an
instruction which takes that much time unless you have a multiplier
application to do it. This is the reason many a times it is avoided in
DSP, embedded systems applications and such hacks are needed.
If you're dividing by a constant, the compiler is likley to be able to
figure out how to do it more efficiently. If it fails to do so *and*
if the (measured!) performance cost is significant, then go ahead and
use some hack (but not the one you posted elsewhere in this thread if
you want correct answers).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 6 '07 #94
On Mon, 05 Feb 2007 13:50:42 GMT, rl*@hoekstra-uitgeverij.nl (Richard
Bos) wrote:
>ri*****@cogsci.ed.ac.uk (Richard Tobin) wrote:
>In article <45*****************@news.xs4all.nl>,
Richard Bos <rl*@hoekstra-uitgeverij.nlwrote:
>True, but neither do I want to present him with a cryptic, tenth-of-a-
second flash

??? Why do your assert messages only last a tenth of a second?
>of (to him) unintelligible console text and an immediate
return to his desktop.

Ah. I don't use one of those desktop thingies.

_So_ nice for you.

Most production peons wouldn't know which end of a CLI was which.
>So rather than assert(), my preference is for a
function which can put a quotable, repeatable error message on his
screen and keep it there until he's finished phoning me.

Assert error messages may be cryptic, but they come with a file and
line number. I don't see why they would not be repeatable.

Your species of luser much be about twelve thousand years futher along
the evolutionary ladder than mine. Congratulations.

I wasn't talking about assert() messages that _I_ see, but about those
that the average, Windows-only, can't-remember-any-numbers, Word-is-
complicated data entry employee sees.

Richard
easy

redirect too the output of all asserts
in a file that can grow < xMb limit
file that is "a queue"
and eliminate double assert that look the same

email that file 1 time for month to who make that program
for the first 3 months (if it is not 0lenght)
Feb 9 '07 #95

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

24
by: Teis Draiby | last post by:
In .NET, can I be sure that the result of a division between two integers always is truncated rather that rounded to nearest? Example: 99 / 50 = 1 regards, Teis
1
by: akickdoe22 | last post by:
Please help me finish this program. i have completed the addition and the subtraction parts, but i am stuck on the multiplication and division. any suggestions, hints, code, anyhting. it's not a...
9
by: Marcin | last post by:
How I can make division of two numbers placed in arrays, example: short int a = {2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2}; short int b =...
17
by: seb.haase | last post by:
Hi, Is it true that that "Python 3000" is dead ? Honestly I think that e.g. changing 5/2 to be 2.5 (instead of 2) would just break to much code :-( On the otherhand I'm using Python as "Matlab...
13
by: Sri | last post by:
Hi, Is there anyway I can implement division in C without using the '/' operator? Can I use bit aritmetic or such? Thanks, Sri
10
by: Mike S | last post by:
Does anyone know the logic behind why in VB.NET the result of a floating-point division ('/') is -rounded- on being converted to an integer type, such as with statements like Dim x As Integer =...
2
by: kermit | last post by:
For a long time,, There has been a discussion of trueFor division versus integer division in Python. I myslef prefer that / be used for integer division since almost always, I want the...
31
by: krypto.wizard | last post by:
How to divide a number by 7 efficiently without using - or / operator. We can use the bit operators. I was thinking about bit shift operator but I don't know the correct answer.
16
by: spl | last post by:
To increase the performance, how to change the / operator with bitwise operators? for ex: 25/5, 225/25 or 25/3 or any division, but I am not bothered of any remainder.
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.