How to sum two integers without using arithmetic operators in C/C++?
Last Updated :
20 Nov, 2023
Given two integers a and b, how can we evaluate the sum a + b without using operators such as +, -, ++, --, ...?
Method 1 (Using pointers)
An interesting way would be:
CPP
// May not work with C++ compilers and
// may produce warnings in C.
// Returns sum of 'a' and 'b'
int sum(int a, int b)
{
char *p = a;
return (int)&p[b];
}
Despite its awkwardness at first sight, we can easily understand what is happening. First, we created a pointer p. The value of a pointer is a memory address. In this case, the value of p is the address a.
Remember: p points to position a. In that example, if we want to know the value of position a (999) we ask to *p. If we want to know the address of variable a (41), we ask to &a. If we evaluated p[b], we'd get the value of memory in position p + b. In fact, we evaluate &p[b], which is the same as getting address p + b without accessing its value. As p = a, &p[b] will return the address a + b. We don't want to return a memory address (int*). We want to return an integer (int). So, we cast &p[b] to int. What happens if we change the type of p from char* to int*? Let me fix what I said before: When we evaluate p[b] we don't evaluate p + b. We evaluate p + sizeof(*p) * b. Why? Imagine this example: Variables of type int occupies fours positions in the memory.
This sizeof(*p) considers the quantity of positions each variable occupies in the memory. We want to evaluate p + b. In other words, we want sizeof(*p) equals to 1. Consequently, if *p is a char, we're happy.
Method 2 (Using bitwise operators)
Let's look the sum's truth table (forgive the carry for now): Looking carefully, we notice that the sum's and xor's truth table are the same. It's 1 only when the input differs. Now, how can we detect carry? Let's look the carry's truth table.
Looking carefully, we notice that the sum's and xor's truth table are the same. It's 1 only when the input differs. Now, how can we detect carry? Let's look the carry's truth table.
Looking carefully one more time, we notice that the carry's and logical and's truth table are identicals. Now, we have to shift a & 1 to left and sum with a ^ b. However, these operations may have carries as well. No problem, just sum a ^ b with a & 1 shifted to left recursively.
CPP
// Returns sum of a and b using bitwise
// operators.
int sum(int a, int b)
{
int s = a ^ b;
int carry = a & b;
if (carry == 0) return s;
else return sum(s, carry << 1);
}
This solution has been discussed here.
Method 3 (Using printf)
Let's remember some facts:
- The printf returns the number of characters printed successfully.
- The specifier %*c requests two parameters: The first one is the customized width and the second is character. For example, printf("%*c", 5, 'a') will print " a".
- The special character '\r' returns the cursor from the beginning of output string. For example, printf("abcd\r12") will print "12cd".
Keeping that in mind, we can understand this function:
CPP
// Returns sum of a and b using printf
// Constraints: a, b > 0.
int sum(int a, int b)
{
return printf("%*c%*c", a, '\r', b, '\r');
}
This solution has been discussed here.
Method 4 (using conversion)
Unlike above other methods, it doesn't shows any error or warning in both C and C++.
Here, we add 2 integers using conversion.
C++
// CPP program to check if a given input is a valid integer
// or a string
#include <bits/stdc++.h>
using namespace std;
int sum(int a, int b) { return (long)&((char*)(long)a)[b]; }
int main()
{
int st = 12;
int pt = 122;
int ans = sum(st, pt);
printf("%d", ans);
return 0;
}
// This code is contributed by Susobhan Akhuli
C
// C program to check if a given input is a valid integer or
// a string
#include <stdio.h>
int sum(int a, int b) { return (long)&((char*)(long)a)[b]; }
int main()
{
int st = 12;
int pt = 122;
int ans = sum(st, pt);
printf("%d", ans);
return 0;
}
// This code is contributed by Susobhan Akhuli
Time Complexity: O(1)
Auxiliary Space: O(1)
Similar Reads
Subtract two numbers without using arithmetic operators
Write a function subtract(x, y) that returns x-y where x and y are integers. The function should not use any of the arithmetic operators (+, ++, â, -, .. etc). The idea is to use bitwise operators. Addition of two numbers has been discussed using Bitwise operators. Like addition, the idea is to use
8 min read
Add two numbers without using arithmetic operators
Given two integers a and b, the task is to find the sum of a and b without using + or - operators. Examples: Input: a = 10, b = 30Output: 40Input: a = -1, b = 2Output: 1Approach:The approach is to add two numbers using bitwise operations. Let's first go through some observations: a & b will have
5 min read
To find sum of two numbers without using any operator
Write a program to find sum of positive integers without using any operator. Only use of printf() is allowed. No other library function can be used.Solution It's a trick question. We can use printf() to find sum of two numbers as printf() returns the number of characters printed. The width field in
9 min read
Set a variable without using Arithmetic, Relational or Conditional Operator
Given three integers a, b and c where c can be either 0 or 1. Without using any arithmetic, relational and conditional operators set the value of a variable x based on below rules - If c = 0 x = a Else // Note c is binary x = b. Examples: Input: a = 5, b = 10, c = 0; Output: x = 5 Input: a = 5, b =
2 min read
C++ program to divide a number by 3 without using *, / , +, -, % operators
For a given positive number we need to divide a number by 3 without using any of these *, /, +, â % operatorsExamples: Input : 48 Output : 16 Input : 16 Output : 5 Algorithm Take a number num, sum = 0while(num>3), shift the number left by 2 bits and sum = add(num >> 2, sum). Create a functi
2 min read
Subtract 1 without arithmetic operators
Write a program to subtract one from a given number. The use of operators like â+â, â-â, â*â, â/â, â++â, âââ â¦etc are not allowed. Examples: Input: 12Output: 11Input: 6Output: 5Bitwise Subtraction ApproachTo subtract 1 from a number x (say 0011001000), flip all the bits after the rightmost 1 bit (we
5 min read
Arithmetic operations with std::bitset in C++
A bitset is an array of boolean values, but each boolean value is not stored separately. Instead, bitset optimizes the space such that each bool takes 1-bit space only, so space taken by bitset say, bs is less than that of bool bs[N] and vector<bool> bs(N). However, a limitation of bitset is,
3 min read
Sum of array using pointer arithmetic
Given an array, write a program to find the sum of array using pointers arithmetic. In this program we make use of * operator . The * (asterisk) operator denotes the value of variable. The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the mem
2 min read
Implement *, - and / operations using only + arithmetic operator
Given two numbers, perform multiplication, subtraction, and division operations on them, using '+' arithmetic operator only. Operations can be performed as follows: Subtraction :- a - b = a + (-1)*b. Multiplication :- a * b = a + a + a ... b times. Division :- a / b = continuously subtract b from a
12 min read
Multiply two integers without using multiplication, division and bitwise operators, and no loops
By making use of recursion, we can multiply two integers with the given constraints. To multiply x and y, recursively add x y times. Approach: Since we cannot use any of the given symbols, the only way left is to use recursion, with the fact that x is to be added to x y times. Base case: When the nu
9 min read