Calculate square of a number without using *, / and pow()
Last Updated :
29 Mar, 2023
Given an integer n, calculate the square of a number without using *, / and pow().
Examples :
Input: n = 5
Output: 25
Input: 7
Output: 49
Input: n = 12
Output: 144
A Simple Solution is to repeatedly add n to result.
Below is the implementation of this idea.
C++
// Simple solution to calculate square without
// using * and pow()
#include <iostream>
using namespace std;
int square(int n)
{
// handle negative input
if (n < 0)
n = -n;
// Initialize result
int res = n;
// Add n to res n-1 times
for (int i = 1; i < n; i++)
res += n;
return res;
}
// Driver code
int main()
{
for (int n = 1; n <= 5; n++)
cout << "n = " << n << ", n^2 = " << square(n)
<< endl;
return 0;
}
Java
// Java Simple solution to calculate
// square without using * and pow()
import java.io.*;
class GFG {
public static int square(int n)
{
// handle negative input
if (n < 0)
n = -n;
// Initialize result
int res = n;
// Add n to res n-1 times
for (int i = 1; i < n; i++)
res += n;
return res;
}
// Driver code
public static void main(String[] args)
{
for (int n = 1; n <= 5; n++)
System.out.println("n = " + n
+ ", n^2 = " + square(n));
}
}
// This code is contributed by sunnysingh
Python3
# Simple solution to
# calculate square without
# using * and pow()
def square(n):
# handle negative input
if (n < 0):
n = -n
# Initialize result
res = n
# Add n to res n-1 times
for i in range(1, n):
res += n
return res
# Driver Code
for n in range(1, 6):
print("n =", n, end=", ")
print("n^2 =", square(n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# Simple solution to calculate
// square without using * and pow()
using System;
class GFG {
public static int square(int n)
{
// handle negative input
if (n < 0)
n = -n;
// Initialize result
int res = n;
// Add n to res n-1 times
for (int i = 1; i < n; i++)
res += n;
return res;
}
// Driver code
public static void Main()
{
for (int n = 1; n <= 5; n++)
Console.WriteLine("n = " + n
+ ", n^2 = " + square(n));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP implementation to
// calculate square
// without using * and pow()
function square($n)
{
// handle negative input
if ($n < 0) $n = -$n;
// Initialize result
$res = $n;
// Add n to res n-1 times
for ($i = 1; $i < $n; $i++)
$res += $n;
return $res;
}
// Driver Code
for ($n = 1; $n<=5; $n++)
echo "n = ", $n, ", ", "n^2 = ",
square($n), "\n ";
// This code is contributed by Ajit
?>
JavaScript
<script>
// Simple solution to calculate square without
// using * and pow()
function square(n)
{
// handle negative input
if (n < 0)
n = -n;
// Initialize result
let res = n;
// Add n to res n-1 times
for (let i = 1; i < n; i++)
res += n;
return res;
}
// Driver code
for (let n = 1; n <= 5; n++)
document.write("n= " + n +", n^2 = " + square(n)
+ "<br>");
//This code is contributed by Mayank Tyagi
</script>
Outputn = 1, n^2 = 1
n = 2, n^2 = 4
n = 3, n^2 = 9
n = 4, n^2 = 16
n = 5, n^2 = 25
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach 2:
We can do it in O(Logn) time using bitwise operators. The idea is based on the following fact.
square(n) = 0 if n == 0
if n is even
square(n) = 4*square(n/2)
if n is odd
square(n) = 4*square(floor(n/2)) + 4*floor(n/2) + 1
Examples
square(6) = 4*square(3)
square(3) = 4*(square(1)) + 4*1 + 1 = 9
square(7) = 4*square(3) + 4*3 + 1 = 4*9 + 4*3 + 1 = 49
How does this work?
If n is even, it can be written as
n = 2*x
n2 = (2*x)2 = 4*x2
If n is odd, it can be written as
n = 2*x + 1
n2 = (2*x + 1)2 = 4*x2 + 4*x + 1
floor(n/2) can be calculated using a bitwise right shift operator. 2*x and 4*x can be calculated
Below is the implementation based on the above idea.
C++
// Square of a number using bitwise operators
#include <bits/stdc++.h>
using namespace std;
int square(int n)
{
// Base case
if (n == 0)
return 0;
// Handle negative number
if (n < 0)
n = -n;
// Get floor(n/2) using right shift
int x = n >> 1;
// If n is odd
if (n & 1)
return ((square(x) << 2) + (x << 2) + 1);
else // If n is even
return (square(x) << 2);
}
// Driver Code
int main()
{
// Function calls
for (int n = 1; n <= 5; n++)
cout << "n = " << n << ", n^2 = " << square(n)
<< endl;
return 0;
}
Java
// Square of a number using
// bitwise operators
class GFG {
static int square(int n)
{
// Base case
if (n == 0)
return 0;
// Handle negative number
if (n < 0)
n = -n;
// Get floor(n/2) using
// right shift
int x = n >> 1;
// If n is odd
;
if (n % 2 != 0)
return ((square(x) << 2) + (x << 2) + 1);
else // If n is even
return (square(x) << 2);
}
// Driver code
public static void main(String args[])
{
// Function calls
for (int n = 1; n <= 5; n++)
System.out.println("n = " + n
+ " n^2 = " + square(n));
}
}
// This code is contributed by Sam007
Python3
# Square of a number using bitwise
# operators
def square(n):
# Base case
if (n == 0):
return 0
# Handle negative number
if (n < 0):
n = -n
# Get floor(n/2) using
# right shift
x = n >> 1
# If n is odd
if (n & 1):
return ((square(x) << 2)
+ (x << 2) + 1)
# If n is even
else:
return (square(x) << 2)
# Driver Code
for n in range(1, 6):
print("n = ", n, " n^2 = ",
square(n))
# This code is contributed by Sam007
C#
// Square of a number using bitwise
// operators
using System;
class GFG {
static int square(int n)
{
// Base case
if (n == 0)
return 0;
// Handle negative number
if (n < 0)
n = -n;
// Get floor(n/2) using
// right shift
int x = n >> 1;
// If n is odd
;
if (n % 2 != 0)
return ((square(x) << 2) + (x << 2) + 1);
else // If n is even
return (square(x) << 2);
}
// Driver code
static void Main()
{
for (int n = 1; n <= 5; n++)
Console.WriteLine("n = " + n
+ " n^2 = " + square(n));
}
}
// This code is contributed by Sam0007.
PHP
<?php
// Square of a number using
// bitwise operators
function square($n)
{
// Base case
if ($n==0) return 0;
// Handle negative number
if ($n < 0) $n = -$n;
// Get floor(n/2)
// using right shift
$x = $n >> 1;
// If n is odd
if ($n & 1)
return ((square($x) << 2) +
($x << 2) + 1);
else // If n is even
return (square($x) << 2);
}
// Driver Code
for ($n = 1; $n <= 5; $n++)
echo "n = ", $n, ", n^2 = ", square($n),"\n";
// This code is contributed by ajit
?>
JavaScript
<script>
// Square of a number using bitwise operators
function square(n)
{
// Base case
if (n == 0)
return 0;
// Handle negative number
if (n < 0)
n = -n;
// Get floor(n/2) using right shift
let x = n >> 1;
// If n is odd
if (n & 1)
return ((square(x) << 2) + (x << 2) + 1);
else // If n is even
return (square(x) << 2);
}
// Driver Code
// Function calls
for (let n = 1; n <= 5; n++)
document.write("n = " + n + ", n^2 = " + square(n)
+"<br>");
//This code is contributed by Mayank Tyagi
</script>
Outputn = 1, n^2 = 1
n = 2, n^2 = 4
n = 3, n^2 = 9
n = 4, n^2 = 16
n = 5, n^2 = 25
Time Complexity: O(log n)
Auxiliary Space: O(log n) as well, as the number of function calls stored in the call stack will be logarithmic to the size of the input
Approach 3:
For a given number `num` we get square of it by multiplying number as `num * num`.
Now write one of `num` in square `num * num` in terms of power of `2`. Check below examples.
Eg: num = 10, square(num) = 10 * 10
= 10 * (8 + 2) = (10 * 8) + (10 * 2)
num = 15, square(num) = 15 * 15
= 15 * (8 + 4 + 2 + 1) = (15 * 8) + (15 * 4) + (15 * 2) + (15 * 1)
Multiplication with power of 2's can be done by left shift bitwise operator.
Below is the implementation based on the above idea.
C++
// Simple solution to calculate square without
// using * and pow()
#include <iostream>
using namespace std;
int square(int num)
{
// handle negative input
if (num < 0) num = -num;
// Initialize result
int result = 0, times = num;
while (times > 0)
{
int possibleShifts = 0, currTimes = 1;
while ((currTimes << 1) <= times)
{
currTimes = currTimes << 1;
++possibleShifts;
}
result = result + (num << possibleShifts);
times = times - currTimes;
}
return result;
}
// Driver code
int main()
{
// Function calls
for (int n = 10; n <= 15; ++n)
cout << "n = " << n << ", n^2 = " << square(n) << endl;
return 0;
}
// This code is contributed by sanjay235
Java
// Simple solution to calculate square
// without using * and pow()
import java.io.*;
class GFG{
public static int square(int num)
{
// Handle negative input
if (num < 0)
num = -num;
// Initialize result
int result = 0, times = num;
while (times > 0)
{
int possibleShifts = 0,
currTimes = 1;
while ((currTimes << 1) <= times)
{
currTimes = currTimes << 1;
++possibleShifts;
}
result = result + (num << possibleShifts);
times = times - currTimes;
}
return result;
}
// Driver code
public static void main(String[] args)
{
for(int n = 10; n <= 15; ++n)
{
System.out.println("n = " + n +
", n^2 = " +
square(n));
}
}
}
// This code is contributed by RohitOberoi
Python3
# Simple solution to calculate square without
# using * and pow()
def square(num):
# Handle negative input
if (num < 0):
num = -num
# Initialize result
result, times = 0, num
while (times > 0):
possibleShifts, currTimes = 0, 1
while ((currTimes << 1) <= times):
currTimes = currTimes << 1
possibleShifts += 1
result = result + (num << possibleShifts)
times = times - currTimes
return result
# Driver Code
# Function calls
for n in range(10, 16):
print("n =", n, ", n^2 =", square(n))
# This code is contributed by divyesh072019
C#
// Simple solution to calculate square
// without using * and pow()
using System;
class GFG {
static int square(int num)
{
// Handle negative input
if (num < 0)
num = -num;
// Initialize result
int result = 0, times = num;
while (times > 0)
{
int possibleShifts = 0,
currTimes = 1;
while ((currTimes << 1) <= times)
{
currTimes = currTimes << 1;
++possibleShifts;
}
result = result + (num << possibleShifts);
times = times - currTimes;
}
return result;
}
static void Main() {
for(int n = 10; n <= 15; ++n)
{
Console.WriteLine("n = " + n +
", n^2 = " +
square(n));
}
}
}
// This code is contributed by divyeshrabadiy07
JavaScript
<script>
// Simple solution to calculate square without
// using * and pow()
function square(num)
{
// handle negative input
if (num < 0) num = -num;
// Initialize result
let result = 0, times = num;
while (times > 0)
{
let possibleShifts = 0, currTimes = 1;
while ((currTimes << 1) <= times)
{
currTimes = currTimes << 1;
++possibleShifts;
}
result = result + (num << possibleShifts);
times = times - currTimes;
}
return result;
}
// Driver code
// Function calls
for (let n = 10; n <= 15; ++n)
document.write("n = " + n + ", n^2 = " + square(n) + "<br>");
//This code is contributed by Mayank Tyagi
</script>
Outputn = 10, n^2 = 100
n = 11, n^2 = 121
n = 12, n^2 = 144
n = 13, n^2 = 169
n = 14, n^2 = 196
n = 15, n^2 = 225
Time Complexity: O(logn)
Auxiliary Space: O(1)
Thanks to Sanjay for approach 3 solution.
C++
// Simple solution to calculate square without
// using * and pow()
#include <iostream>
using namespace std;
int square(int num)
{
// handle negative input
if (num < 0)
num = -num;
// Initialize power of 2 and result
int power = 0, result = 0;
int temp = num;
while (temp) {
if (temp & 1) {
// result=result+(num*(2^power))
result += (num << power);
}
power++;
// temp=temp/2
temp = temp >> 1;
}
return result;
}
// Driver code
int main()
{
// Function calls
for (int n = 10; n <= 15; ++n)
cout << "n = " << n << ", n^2 = " << square(n)
<< endl;
return 0;
}
// This code is contributed by Aditya Verma
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
// java program for Simple solution to calculate square without
// using * and pow()
// This code is contributed by Aditya Verma
public class Main {
public static int square(int num)
{
// handle negative input
if (num < 0)
num = -num;
// Initialize power of 2 and result
int power = 0, result = 0;
int temp = num;
while (temp > 0) {
if ((temp & 1) > 0) {
// result=result+(num*(2^power))
result += (num << power);
}
power++;
// temp=temp/2
temp = temp >> 1;
}
return result;
}
public static void main(String[] args) {
// Function calls
for (int n = 10; n <= 15; ++n)
System.out.println("n = " + n + ", n^2 = " + square(n));
}
}
// The code is contributed by Nidhi goel.
Python3
def square(num):
# handle negative input
if num < 0:
num = -num
# Initialize power of 2 and result
power, result = 0, 0
temp = num
while temp:
if temp & 1:
# result=result+(num*(2^power))
result += (num << power)
power += 1
# temp=temp/2
temp = temp >> 1
return result
# Driver code
for n in range(10, 16):
print(f"n = {n}, n^2 = {square(n)}")
JavaScript
// Simple solution to calculate square without
// using * and pow()
function square(num) {
// handle negative input
if (num < 0)
num = -num;
// Initialize power of 2 and result
let power = 0, result = 0;
let temp = num;
while (temp) {
if (temp & 1) {
// result=result+(num*(2^power))
result += (num << power);
}
power++;
// temp=temp/2
temp = temp >> 1;
}
return result;
}
// Driver code
// Function calls
for (let n = 10; n <= 15; ++n)
console.log(`n = ${n}, n^2 = ${square(n)}`);
// This code is contributed by phasing17
C#
// Simple solution to calculate square without
// using * and pow()
using System;
public class Program
{
public static int Square(int num)
{
// handle negative input
if (num < 0)
num = -num;
// Initialize power of 2 and result
int power = 0, result = 0;
int temp = num;
while (temp > 0)
{
if ((temp & 1) > 0)
{
// result=result+(num*(2^power))
result += (num << power);
}
power++;
// temp=temp/2
temp = temp >> 1;
}
return result;
}
public static void Main()
{
// Function calls
for (int n = 10; n <= 15; ++n)
Console.WriteLine("n = " + n + ", n^2 = " + Square(n));
}
}
// Contributed by adityasha4x71
Outputn = 10, n^2 = 100
n = 11, n^2 = 121
n = 12, n^2 = 144
n = 13, n^2 = 169
n = 14, n^2 = 196
n = 15, n^2 = 225
Time Complexity: O(logn)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem