add without carry

Peter Otten __peter__ at web.de
Fri Sep 15 11:56:51 CEST 2006


Hugh wrote:

> Sorry, here's an example...
> 
> 5+7=12
> 
> added without carrying, 5+7=2
> 
> i.e the result is always less than 10
> 
> I've been thinking some more about this and my brain is starting to
> work something out... I just wondered if there was a function in python
> math to do this automatically...

>>> (5 + 7) % 10
2

In this context '%' is called 'modulo operator'. What John and Marc
suggested is basically the same operation for the special case of binary
numbers, i. e.

a % b == a & (b-1)

if a >= 0 and b == 2**N.

Peter



More information about the Python-list mailing list