Infinite loop while adding two integers using bitwise operations?

2024/10/3 21:21:19

I am trying to solve a problem, using python code, which requires me to add two integers without the use of '+' or '-' operators. I have the following code which works perfectly for two positive numbers:

def getSum(self, a, b):while (a & b):x = a & by = a ^ ba = x << 1b = yreturn a ^ b

This piece of code works perfectly if the input is two positive integers or two negative integers but it fails when one number is positive and other is negative. It goes into an infinite loop. Any idea as to why this might be happening?

EDIT: Here is the link discussing the code fix for this.

Answer

Python 3 has arbitrary-precision integers ("bignums"). This means that anytime x is negative, x << 1 will make x a negative number with twice the magnitude. Zeros shifting in from the right will just push the number larger and larger.

In two's complement, positive numbers have a 0 in the highest bit and negative numbers have a 1 in the highest bit. That means that, when only one of a and b is negative, the top bits of a and b will differ. Therefore, x will be positive (1 & 0 = 0) and y will be negative (1 ^ 0 = 1). Thus the new a will be positive (x<<1) and the new b will be negative (y).

Now: arbitrary-precision negative integers actually have an infinite number of leading 1 bits, at least mathematicallly. So a is a larger and larger positive number, expanding by 2 each iteration. b keeps getting more and more leading 1 bits added to be able to carry out the bitwise & and ^ with a. Thus whatever bits of a are turned on line up with one of the added 1 bits of b, so a & b is always true, so the loop runs forever.

https://en.xdnf.cn/q/70688.html

Related Q&A

When is pygame.init() needed?

I am studying pygame and in the vast majority of tutorials it is said that one should run pygame.init() before doing anything. I was doing one particular tutorial and typing out the code as one does an…

mypy overrides in toml are ignored?

The following is a simplified version of the toml file example from the mypy documentation: [tool.mypy] python_version = "3.7" warn_return_any = true warn_unused_configs = true[[tool.mypy.ove…

/usr/bin/env: python2.6: No such file or directory error

I have python2.6, python2.7 and python3 in my /usr/lib/I am trying to run a file which has line given below in it as its first line#!/usr/bin/env python2.6after trying to run it it gives me following e…

pandas, dataframe, groupby, std

New to pandas here. A (trivial) problem: hosts, operations, execution times. I want to group by host, then by host+operation, calculate std deviation for execution time per host, then by host+operation…

Count occurrences of a couple of specific words

I have a list of words, lets say: ["foo", "bar", "baz"] and a large string in which these words may occur. I now use for every word in the list the "string".coun…

numpy: how to fill multiple fields in a structured array at once

Very simple question: I have a structured array with multiple columns and Id like to fill only some of them (but more than one) with another preexisting array.This is what Im trying:strc = np.zeros(4, …

Combine date column and time column into datetime column

I have a Pandas dataframe like this; (obtained by parsing an excel file)| | COMPANY NAME | MEETING DATE | MEETING TIME| --------------------------------------------------------…

Matplotlib Plot Lines Above Each Bar

I would like to plot a horizontal line above each bar in this chart. The y-axis location of each bar depends on the variable target. I want to use axhline, if possible, or Line2D because I need to be …

Flask-SQLAlchemy Lower Case Index - skipping functional, not supported by SQLAlchemy reflection

First off. Apologies if this has been answered but I can not find the answer any where.I need to define a lowercase index on a Flask-SQLAlchemy object.The problem I have is I need a models username and…

pip listing global packages in active virtualenv

After upgrading pip from 1.4.x to 1.5 pip freeze outputs a list of my globally installed (system) packages instead of the ones installed inside of my virtualenv. Ive tried downgrading to 1.4 again but …