Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Divide and Conquer
  • MCQs on Divide and Conquer
  • Tutorial on Divide & Conquer
  • Binary Search
  • Merge Sort
  • Quick Sort
  • Calculate Power
  • Strassen's Matrix Multiplication
  • Karatsuba Algorithm
  • Divide and Conquer Optimization
  • Closest Pair of Points
Open In App
Next Article:
C++ Program to Find Factorial of a Number Using Iteration
Next article icon

C++ Program To Find Power Without Using Multiplication(*) And Division(/) Operators

Last Updated : 17 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Method 1 (Using Nested Loops):
We can calculate power by using repeated addition. 
For example to calculate 5^6. 
1) First 5 times add 5, we get 25. (5^2) 
2) Then 5 times add 25, we get 125. (5^3) 
3) Then 5 times add 125, we get 625 (5^4) 
4) Then 5 times add 625, we get 3125 (5^5) 
5) Then 5 times add 3125, we get 15625 (5^6) 

C++
// C++ code for power function  #include <bits/stdc++.h> using namespace std;  // Works only if a >= 0  // and b >= 0  int pow(int a, int b)  {      if (b == 0)          return 1;      int answer = a;      int increment = a;      int i, j;      for(i = 1; i < b; i++)      {          for(j = 1; j < a; j++)          {              answer += increment;          }          increment = answer;      }      return answer;  }   // Driver Code int main()  {      cout << pow(5, 3);      return 0;  }   // This code is contributed by rathbhupendra 

Output : 

125

Time Complexity: O(a * b)

Auxiliary Space: O(1)

Method 2 (Using Recursion) 
Recursively add a to get the multiplication of two numbers. And recursively multiply to get a raise to the power b.

C++
// C++ program to implement  // the above approach #include<bits/stdc++.h> using namespace std;  // A recursive function  // to get x*y int multiply(int x, int y) {     if(y)         return (x + multiply(x,                  y - 1));     else         return 0; }  // A recursive function to get a^b // Works only if a >= 0 and b >= 0 int pow(int a, int b) {     if(b)         return multiply(a,                          pow(a, b - 1));     else         return 1; }   // Driver Code int main() {     cout << pow(5, 3);     getchar();     return 0; }  // This code is contributed by Akanksha Rai 

Output : 

125

Time Complexity: O(b)

Auxiliary Space: O(b)

Method 3 (Using bit masking) 

we can a^n (let's say 3^5) as 3^4 * 3^0 * 3^1 = 3^, so we can represent 5 as its binary i.e. 101

C++
// C++ program to implement // the above approach #include <iostream> using namespace std;  // Function calculating power long long pow(int a, int n) {     int ans = 1;       while(n > 0)       {           // Calculate last bit(right most)            // bit of n           int last_bit = n&1;                      // if last bit is 1 then multiply            // ans and a           if(last_bit)           {             ans = ans*a;           }              // Make a equal to square of a as on        // every succeeding bit it got squared        // like a^0, a^1, a^2, a^4, a^8       a = a * a;       n = n >> 1;     }       return ans; }  // Driver code int main()  {     cout << pow(3, 5);     return 0; } 

Time Complexity: O(log n)

Auxiliary Space: O(1)


Next Article
C++ Program to Find Factorial of a Number Using Iteration
author
kartik
Improve
Article Tags :
  • Divide and Conquer
  • Mathematical
  • C++ Programs
  • C++
  • DSA
  • C++ Basic Programs
Practice Tags :
  • CPP
  • Divide and Conquer
  • Mathematical

Similar Reads

  • C++ Program to Find Factorial of a Number Using Iteration
    Factorial of a number n is the product of all integers from 1 to n. In this article, we will learn how to find the factorial of a number using iteration in C++. Example Input: 5Output: Factorial of 5 is 120Factorial of Number Using Iteration in C++To find the factorial of a given number we can use l
    2 min read
  • C++ Program to find whether a no is power of two
    Given a positive integer, write a function to find if it is a power of two or not.Examples : Input : n = 4 Output : Yes 22 = 4 Input : n = 7 Output : No Input : n = 32 Output : Yes 25 = 32 1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then nu
    2 min read
  • C++ Program To Multiply Two Floating-Point Numbers
    Here, we will see how to multiply two floating-point numbers using the C++ program. Floating point numbers are numbers that include both integer part and fractional parts represented in the form of decimal and exponential values. float data type is used to store floating point values. For example In
    2 min read
  • C++ Program to Find Factorial of a Number Using Dynamic Programming
    The Factorial of a number N can be defined as the product of numbers from 1 to the number N. More formally factorial of n can be defined by function, [Tex]f(n) = 1 \times 2 \times 3 \times... \ n[/Tex] In this article, we will learn how to find the factorial of a number using dynamic programming in
    2 min read
  • C++ Program to Perform Calculations in Pure Strings
    Given a string of operations containing three operands for each operation "type of command", "first operand", and "second operand". Calculate all the commands given in this string format. In other words, you will be given a pure string that will ask you to perform an operation and you have to perfor
    5 min read
  • C++ Program to Find Factorial of a Large Number Using Recursion
    Given a large number N, task is to find the factorial of N using recursion. Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. Examples: Input : N = 100Output : 93326215443944152681699238856266
    2 min read
  • C++ Program to find sum of even factors of a number
    Given a number n, the task is to find the even factor sum of a number. Examples: Input : 30 Output : 48 Even dividers sum 2 + 6 + 10 + 30 = 48 Input : 18 Output : 26 Even dividers sum 2 + 6 + 18 = 26 Let p1, p2, … pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respect
    3 min read
  • How to Parse Mathematical Expressions in a C++ String?
    In C++, strings are sequences of characters stored in a char array. Strings are used to store words and text. We can also store mathematical expressions in this string. In this article, we will explore how to parse mathematical expressions in a C++ String. Example: Input:expression = (3 + 4) * 2 / (
    5 min read
  • C++ Program To Find Armstrong Numbers Between Two Integers
    A positive integer with digits a, b, c, d... is called an Armstrong number of order n if following condition is satisfied.  abcd... = an + bn + cn + dn +... 153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153 Therefore, 153 is an Armstrong number. Examples: Input: 100 400 Output: 153 370 371 Explanatio
    2 min read
  • C++ Program to Check Whether Number is Even or Odd
    A number is even if it is completely divisible by 2 and it is odd if it is not completely divisible by 2. In this article, we will learn how to check whether a number is even or odd in C++. Examples Input: n = 11Output: OddExplanation: Since 11 is not completely divisible by 2, it is an odd number.
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences