S
sudharsan
give a fast way to multiply a number by 7
sudharsan said:give a fast way to multiply a number by 7
sudharsan said:give a fast way to multiply a number by 7
Most C compilers know a reasonable compromise between generated codeVladimir said:Think along the lines of:
x*7 = x*(4+2+1)
How is this related to C?
Tim said:Most C compilers know a reasonable compromise between generated code
size and speed for their target architecture.
Vladimir said:I know that. The OP's question is obviously a homework or some-such.
If that's the case it'll still be useful for him to try and implement
the above. For good measure, I probably should have added The First
Rule of Optimisation:
1. DON'T
Other rules, for more advanced users can be found elsegroup. ;-)
pemo said:If you're thinking of 'shifting' - how's that going to work with floats?
give a fast way to multiply a number by 7
slow on P4pablo said:x*7 = (x<<2)+(x<<1)+x
Vladimir said:I was, yes. It won't, but I think the answer was at least as good as
the question.
slow on P4
Lew said:-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
P'haps you are looking for something other than
number = number * 7;
If so, then you could use shifts and additions
In algebra, you learn that
N * 7 = N * (4 + 2 + 1)
= (N * 4) + (N * 2) + (N * 1)
In binary maths, multiplication by a power of two can be accomplished with an
integer number of left shifts
N * 4 = N << 2
N * 2 = N << 1
N * 1 = N << 0
Substituting for common values gives
N * 7 = (N << 2) + (N << 1) + (N << 0)
Inverting order for algorithmic efficiency gives
N * 7 = (N << 0) + (N << 1) + (N << 2)
You can code this as
unsigned int number = 3;
number = (number) + (number << 1) + (number << 2);
But, this is likely to be /less/ efficient than
number = number * 7;
sudharsan said:give a fast way to multiply a number by 7
pete said:Lew Pitcher wrote:
If I was looking for a shifty way, it would be:
((number << 3) - number)
Ian said:I'd wondered about that: does it have funny overflow behaviour
(ie different to that of 7*number)?
sudharsan said:give a fast way to multiply a number by 7
pablo reda said:x*7 = (x<<2)+(x<<1)+x
sudharsan said:give a fast way to multiply a number by 7
"pablo reda said:x*7 = (x<<2)+(x<<1)+x
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.