The Wayback Machine - https://web.archive.org/web/20240926122650/https://www.geeksforgeeks.org/power-set/
Open In App

Power Set

Last Updated : 13 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
43.3%
98.5K

Power Set: Power set P(S) of a set S is the set of all subsets of S. For example S = {a, b, c} then P(s) = {{}, {a}, {b}, {c}, {a,b}, {a, c}, {b, c}, {a, b, c}}. If S has n elements in it then P(s) will have 2n elements

Example: 

Input : ab
Output : “”, “a”, “b”, “ab”

Input : abc
Output : “”, “a”, “b”, “c”, “ab”, “bc”, “ac”, “abc”

Input : a
Output : “”, “a”

Using Binary Representation of Numbers from 0 to 2^n – 1

For a given set[] S, the power set can be found by generating all binary numbers between 0 and 2n-1, where n is the size of the set. 

Set  = [a,b,c]
power_set_size = pow(2, 3) = 8
Run for binary counter = 000 to 111. We consider a when the last bit is set and do not consider if the last bit is not set. We do the same thing for b and second bit, and for c and first bit.

Value of Counter            Subset
   000                    -> Empty set
   001                    -> a
   010                    -> b
   011                    -> ab
   100                    -> c
   101                    -> ac
   110                    -> bc
   111                    -> abc

Detailed Steps:

1. Get the size of power set
      powet_set_size = pow(2, set_size)
2  Loop for counter from 0 to pow_set_size
    (a) Loop for i = 0 to set_size
         (i) If ith bit in counter is set
                Print ith element from set for this subset
   (b) Print separator for subsets i.e., newline

Below is the implementation of the above approach.

C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to print all the power set
void printPowerSet(char* set, int set_size)
{
    // Set_size of power set of a set with set_size
    // n is (2^n-1)
    unsigned int pow_set_size = pow(2, set_size);
    int counter, j;

    // Run from counter 000..0 to 111..1
    for (counter = 0; counter < pow_set_size; counter++) {
        for (j = 0; j < set_size; j++) {
          
            // Check if jth bit in the counter is set
            // If set then print jth element from set
            if (counter & (1 << j))
                cout << set[j];
        }
        cout << endl;
    }
}

/*Driver code*/
int main()
{
    char set[] = { 'a', 'b', 'c' };
    printPowerSet(set, 3);
    return 0;
}

// This code is contributed by SoM15242
C
#include <stdio.h>
#include <math.h>

void printPowerSet(char *set, int set_size)
{
    /*set_size of power set of a set with set_size
      n is (2**n -1)*/
    unsigned int pow_set_size = pow(2, set_size);
    int counter, j;

    /*Run from counter 000..0 to 111..1*/
    for(counter = 0; counter < pow_set_size; counter++)
    {
      for(j = 0; j < set_size; j++)
       {
          /* Check if jth bit in the counter is set
             If set then print jth element from set */
          if(counter & (1<<j))
            printf("%c", set[j]);
       }
       printf("\n");
    }
}

/*Driver program to test printPowerSet*/
int main()
{
    char set[] = {'a','b','c'};
    printPowerSet(set, 3);
    return 0;
}
Java
// Java program for power set
import java .io.*;

public class GFG {
    
    static void printPowerSet(char []set,
                            int set_size)
    {
        
        /*set_size of power set of a set
        with set_size n is (2**n -1)*/
        long pow_set_size = 
            (long)Math.pow(2, set_size);
        int counter, j;
    
        /*Run from counter 000..0 to
        111..1*/
        for(counter = 0; counter < 
                pow_set_size; counter++)
        {
            for(j = 0; j < set_size; j++)
            {
                /* Check if jth bit in the 
                counter is set If set then 
                print jth element from set */
                if((counter & (1 << j)) > 0)
                    System.out.print(set[j]);
            }
            
            System.out.println();
        }
    }
    
    // Driver program to test printPowerSet
    public static void main (String[] args)
    {
        char []set = {'a', 'b', 'c'};
        printPowerSet(set, 3);
    }
}

// This code is contributed by anuj_67.
Python
# python3 program for power set

import math;

def printPowerSet(set,set_size):
    
    # set_size of power set of a set
    # with set_size n is (2**n -1)
    pow_set_size = (int) (math.pow(2, set_size));
    counter = 0;
    j = 0;
    
    # Run from counter 000..0 to 111..1
    for counter in range(0, pow_set_size):
        for j in range(0, set_size):
            
            # Check if jth bit in the 
            # counter is set If set then 
            # print jth element from set 
            if((counter & (1 << j)) > 0):
                print(set[j], end = "");
        print("");

# Driver program to test printPowerSet
set = ['a', 'b', 'c'];
printPowerSet(set, 3);

# This code is contributed by mits.
C#
// C# program for power set
using System;

class GFG {
    
    static void printPowerSet(char []set,
                            int set_size)
    {
        /*set_size of power set of a set
        with set_size n is (2**n -1)*/
        uint pow_set_size = 
              (uint)Math.Pow(2, set_size);
        int counter, j;
    
        /*Run from counter 000..0 to
        111..1*/
        for(counter = 0; counter < 
                   pow_set_size; counter++)
        {
            for(j = 0; j < set_size; j++)
            {
                /* Check if jth bit in the 
                counter is set If set then 
                print jth element from set */
                if((counter & (1 << j)) > 0)
                    Console.Write(set[j]);
            }
            
            Console.WriteLine();
        }
    }
    
    // Driver program to test printPowerSet
    public static void Main ()
    {
        char []set = {'a', 'b', 'c'};
        printPowerSet(set, 3);
    }
}

// This code is contributed by anuj_67.
JavaScript
<script>
// javascript program for power setpublic 

    function printPowerSet(set, set_size) 
    {

        /*
         * set_size of power set of a set with set_size n is (2**n -1)
         */
        var pow_set_size = parseInt(Math.pow(2, set_size));
        var counter, j;

        /*
         * Run from counter 000..0 to 111..1
         */
        for (counter = 0; counter < pow_set_size; counter++)
        {
            for (j = 0; j < set_size; j++) 
            {
            
                /*
                 * Check if jth bit in the counter is set If set then print jth element from set
                 */
                if ((counter & (1 << j)) > 0)
                    document.write(set[j]);
            }
            document.write("<br/>");
        }
    }

    // Driver program to test printPowerSet
        let set = [ 'a', 'b', 'c' ];
        printPowerSet(set, 3);

// This code is contributed by shikhasingrajput 
</script>
PHP
 <?php
// PHP program for power set

function printPowerSet($set, $set_size)
{

    // set_size of power set of
    // a set with set_size
    // n is (2**n -1)
    $pow_set_size = pow(2, $set_size);
    $counter; $j;

    // Run from counter 000..0 to
    // 111..1
    for($counter = 0; $counter < $pow_set_size;
                                    $counter++)
    {
        for($j = 0; $j < $set_size; $j++)
        {
            
            /* Check if jth bit in 
               the counter is set
               If set then print 
               jth element from set */
            if($counter & (1 << $j))
                echo $set[$j];
        }
        
    echo "\n";
    }
}

    // Driver Code
    $set = array('a','b','c');
    printPowerSet($set, 3);

// This code is contributed by Vishal Tripathi
?>

Output
a
b
ab
c
ac
bc
abc

Time Complexity: O(n2n)
Auxiliary Space: O(1)

Power set using Previous Permutation

In auxiliary array of bool set all elements to 0. That represent an empty set. Set first element of auxiliary array to 1 and generate all permutations to produce all subsets with one element. Then set the second element to 1 which will produce all subsets with two elements, repeat until all elements are included.

Below is the implementation of the above approach.

C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to print all the power set
void printPowerSet(char set[], int n)
{
    bool *contain = new bool[n]{0};
    
    // Empty subset
    cout << "" << endl;
    for(int i = 0; i < n; i++)
    {
        contain[i] = 1;
        // All permutation
        do
        {
            for(int j = 0; j < n; j++)
                if(contain[j])
                    cout << set[j];
            cout << endl;
        } while(prev_permutation(contain, contain + n));
    }
}

/*Driver code*/
int main()
{
    char set[] = {'a','b','c'};
    printPowerSet(set, 3);
    return 0;
}

// This code is contributed by zlatkodamijanic
Java
// Java program for the above approach

import java.util.*;

class GFG
{

  // A function to reverse only the indices in the
  // range [l, r]
  static int[] reverse(int[] arr, int l, int r)
  {
    int d = (r - l + 1) / 2;
    for (int i = 0; i < d; i++) {
      int t = arr[l + i];
      arr[l + i] = arr[r - i];
      arr[r - i] = t;
    }
    return arr;
  }
  // A function which gives previous
  // permutation of the array
  // and returns true if a permutation
  // exists.
  static boolean prev_permutation(int[] str)
  {
    // Find index of the last
    // element of the string
    int n = str.length - 1;

    // Find largest index i such
    // that str[i - 1] > str[i]
    int i = n;
    while (i > 0 && str[i - 1] <= str[i]) {
      i--;
    }

    // If string is sorted in
    // ascending order we're
    // at the last permutation
    if (i <= 0) {
      return false;
    }

    // Note - str[i..n] is sorted
    // in ascending order Find
    // rightmost element's index
    // that is less than str[i - 1]
    int j = i - 1;
    while (j + 1 <= n && str[j + 1] < str[i - 1]) {
      j++;
    }

    // Swap character at i-1 with j
    int temper = str[i - 1];
    str[i - 1] = str[j];
    str[j] = temper;

    // Reverse the substring [i..n]
    str = reverse(str, i, str.length - 1);

    return true;
  }

  // Function to print all the power set
  static void printPowerSet(char[] set, int n)
  {

    int[] contain = new int[n];
    for (int i = 0; i < n; i++)
      contain[i] = 0;

    // Empty subset
    System.out.println();
    for (int i = 0; i < n; i++) {
      contain[i] = 1;

      // To avoid changing original 'contain'
      // array creating a copy of it i.e.
      // "Contain"
      int[] Contain = new int[n];
      for (int indx = 0; indx < n; indx++) {
        Contain[indx] = contain[indx];
      }

      // All permutation
      do {
        for (int j = 0; j < n; j++) {
          if (Contain[j] != 0) {
            System.out.print(set[j]);
          }
        }
        System.out.print("\n");

      } while (prev_permutation(Contain));
    }
  }

  /*Driver code*/
  public static void main(String[] args)
  {
    char[] set = { 'a', 'b', 'c' };
    printPowerSet(set, 3);
  }
}

// This code is contributed by phasing17
Python
# Python3 program for the above approach

# A function which gives previous
# permutation of the array
# and returns true if a permutation
# exists.
def prev_permutation(str):

    # Find index of the last
    # element of the string
    n = len(str) - 1

    # Find largest index i such
    # that str[i - 1] > str[i]
    i = n
    while (i > 0 and str[i - 1] <= str[i]):
        i -= 1

    # If string is sorted in
    # ascending order we're
    # at the last permutation
    if (i <= 0):
        return False

    # Note - str[i..n] is sorted
    # in ascending order Find
    # rightmost element's index
    # that is less than str[i - 1]
    j = i - 1
    while (j + 1 <= n and str[j + 1] < str[i - 1]):
        j += 1

    # Swap character at i-1 with j
    temper = str[i - 1]
    str[i - 1] = str[j]
    str[j] = temper

    # Reverse the substring [i..n]
    size = n-i+1
    for idx in range(int(size / 2)):
        temp = str[idx + i]
        str[idx + i] = str[n - idx]
        str[n - idx] = temp

    return True

# Function to print all the power set
def printPowerSet(set, n):

    contain = [0 for _ in range(n)]

    # Empty subset
    print()

    for i in range(n):
        contain[i] = 1

        # To avoid changing original 'contain'
        # array creating a copy of it i.e.
        # "Contain"
        Contain = contain.copy()

        # All permutation
        while True:
            for j in range(n):
                if (Contain[j]):
                    print(set[j], end="")
            print()
            if not prev_permutation(Contain):
                break

# Driver code
set = ['a', 'b', 'c']
printPowerSet(set, 3)

# This code is contributed by phasing17
C#
// C# program for the above approach

using System;
using System.Linq;
using System.Collections.Generic;

class GFG
{

  // A function which gives previous
  // permutation of the array
  // and returns true if a permutation
  // exists.
  static bool prev_permutation(int[] str)
  {
    // Find index of the last
    // element of the string
    int n = str.Length - 1;

    // Find largest index i such
    // that str[i - 1] > str[i]
    int i = n;
    while (i > 0 && str[i - 1] <= str[i]) {
      i--;
    }

    // If string is sorted in
    // ascending order we're
    // at the last permutation
    if (i <= 0) {
      return false;
    }

    // Note - str[i..n] is sorted
    // in ascending order Find
    // rightmost element's index
    // that is less than str[i - 1]
    int j = i - 1;
    while (j + 1 <= n && str[j + 1] < str[i - 1]) {
      j++;
    }

    // Swap character at i-1 with j
    var temper = str[i - 1];
    str[i - 1] = str[j];
    str[j] = temper;

    // Reverse the substring [i..n]
    int size = n - i + 1;
    Array.Reverse(str, i, size);

    return true;
  }

  // Function to print all the power set
  static void printPowerSet(char[] set, int n)
  {

    int[] contain = new int[n];
    for (int i = 0; i < n; i++)
      contain[i] = 0;

    // Empty subset
    Console.WriteLine();
    for (int i = 0; i < n; i++) {
      contain[i] = 1;

      // To avoid changing original 'contain'
      // array creating a copy of it i.e.
      // "Contain"
      int[] Contain = new int[n];
      for (int indx = 0; indx < n; indx++) {
        Contain[indx] = contain[indx];
      }

      // All permutation
      do {
        for (int j = 0; j < n; j++) {
          if (Contain[j] != 0) {
            Console.Write(set[j]);
          }
        }
        Console.Write("\n");

      } while (prev_permutation(Contain));
    }
  }

  /*Driver code*/
  public static void Main(string[] args)
  {
    char[] set = { 'a', 'b', 'c' };
    printPowerSet(set, 3);
  }
}

// This code is contributed by phasing17
JavaScript
// JavaScript program for the above approach

// A function which gives previous 
// permutation of the array
// and returns true if a permutation 
// exists. 
function prev_permutation(str){    
    // Find index of the last
    // element of the string
    let n = str.length - 1;
 
    // Find largest index i such
    // that str[i - 1] > str[i]
    let i = n;
    while (i > 0 && str[i - 1] <= str[i]){
        i--;
    }   
      
    // If string is sorted in
    // ascending order we're
    // at the last permutation
    if (i <= 0){
        return false;
    }
 
    // Note - str[i..n] is sorted
    // in ascending order Find
    // rightmost element's index
    // that is less than str[i - 1]
    let j = i - 1;
    while (j + 1 <= n && str[j + 1] < str[i - 1]){
        j++;
    }
    
    // Swap character at i-1 with j
    const temper = str[i - 1];
    str[i - 1] = str[j];
    str[j] = temper;
    
    // Reverse the substring [i..n]
    let size = n-i+1;
    for (let idx = 0; idx < Math.floor(size / 2); idx++) {
        let temp = str[idx + i];
        str[idx + i] = str[n - idx];
        str[n - idx] = temp;
    }
    
    return true;
}

// Function to print all the power set
function printPowerSet(set, n){   

    let contain = new Array(n).fill(0);

    // Empty subset
    document.write("<br>");
    for(let i = 0; i < n; i++){
        contain[i] = 1; 
        
        // To avoid changing original 'contain' 
        // array creating a copy of it i.e.
        // "Contain"
        let Contain = new Array(n);
        for(let indx = 0; indx < n; indx++){
            Contain[indx] = contain[indx];
        }

        // All permutation
        do{
            for(let j = 0; j < n; j++){                
                if(Contain[j]){
                    document.write(set[j]);
                }  
            }
            document.write("<br>");
            
        } while(prev_permutation(Contain));
    }
}

/*Driver code*/
const set = ['a','b','c'];
printPowerSet(set, 3);

// This code is contributed by Gautam goel (gautamgoel962)

Output
a
b
c
ab
ac
bc
abc

Time Complexity: O(n2n)
Auxiliary Space: O(n)

Recursive program to generate power set
Refer Power Set in Java for implementation in Java and more methods to print power set.


References: 
http://en.wikipedia.org/wiki/Power_set
 



Previous Article
Next Article

Similar Reads

Check if given number is a power of d where d is a power of 2
Given an integer n, find whether it is a power of d or not, where d is itself a power of 2.Examples: Input : n = 256, d = 16 Output : Yes Input : n = 32, d = 16 Output : No Method 1 Take log of the given number on base d, and if we get an integer then number is power of d. C/C++ Code // CPP program to find if a number is power // of d where d is po
9 min read
Compute power of power k times % m
Given x, k and m. Compute (xxxx...k)%m, x is in power k times. Given x is always prime and m is greater than x. Examples: Input : 2 3 3 Output : 1 Explanation : ((2 ^ 2) ^ 2) % 3 = (4 ^ 2) % 3 = 1 Input : 3 2 3 Output : 0 Explanation : (3^3)%3 = 0 A naive approach is to compute the power of x k times and do modulus operation every time. C/C++ Code
15+ min read
Larger of a^b or b^a (a raised to power b or b raised to power a)
Given two numbers [Tex]$a and b$ [/Tex], find which is greater [Tex]a^b or \, b^a [/Tex].If [Tex]a^b &gt; b^a [/Tex], print a^b is greater If [Tex]a^b &lt; b^a [/Tex], print b^a is greater If [Tex]a^b = b^a [/Tex], print Both are equalExamples: Input : 3 5 Output : a^b is greater 3^5 = 243, 5^3 = 125. Since, 243&gt;125, therefore a^b &gt; b^a. Inpu
5 min read
Find the sum of power of bit count raised to the power B
Given an integer, array A. Find the sum of set bits raised to the power A[i] for each element in A[i].Example: Input: N = 3, A[] = {1, 2, 3}Output: 10Explanation:Set bit of each array element is1 = 1 set bit, 2 = 1 set bit, 3 = 2 set bit store each set bit in b[i].Compute sum of power(b[i], i) where i is ranging from 1 to n., that is sum = power(1,
6 min read
Maximize the product of sum and least power by choosing at most K elements from given value and power Arrays
Given two arrays arr[] and powr[] of size N and an integer K. Every element arr[i] has its respective power powr[i]. The task is to maximize the value of the given function by choosing at most K elements from the array. The function is defined as : f(N) = (arr[i1] + arr[i2] + arr[i3]+.....arr[in]) * min(powr[i1], powr[i2], powr[i3], .....powr[in])
10 min read
Maximum power in N levels from K such that defeating boss at level A[i] increases power by B[i]
Given two arrays a[] and b[] of size N and an integer K. The task is to find the maximum power that can be achieved in N levels with initial power K such that after defeating the ith level boss of strength a[i], power is increased by b[i]. In order to defeat a boss the power should be greater than or equal to his power. Examples: Input: N = 3, K =
7 min read
Find power of power under mod of a prime
Given four numbers A, B, C and M, where M is prime number. Our task is to compute A raised to power (B raised to power C) modulo M. Example: Input : A = 2, B = 4, C = 3, M = 23Output : 643 = 64 so,2^64(mod 23) = 6 A Naive Approach is to calculate res = BC and then calculate Ares % M by modular exponential. The problem of this approach is that we ca
7 min read
Check if a number can be expressed as power | Set 2 (Using Log)
Check if a number can be expressed as x^y (x raised to power y) Given a positive integer n, find if it can be expressed as x^y where y &gt; 1 and x &gt; 0. x and y both are integers.Examples : Input: n = 8 Output: true 8 can be expressed as 2^3 Input: n = 49 Output: true 49 can be expressed as 7^2 Input: n = 48 Output: false 48 can't be expressed a
4 min read
Generate a sequence from first X natural numbers which adds up to S on raising 2 to the power of their lowest set bits
Given two integers X and S, the task is to construct a sequence of distinct integers from the range [1, X] such that the sum of value 2K is equal to S, where K is the position of the first set bit from the end ( 0-based indexing )of the binary representation of each element is S. Examples: Input: X = 3, S = 4Output: 2 3 1Explanation:Summation of 2K
10 min read
Minimum size of set having either element in range [0, X] or an odd power of 2 with sum N
Given two positive integers N and X, the task is to find the size of the smallest set of integers such that the sum of all elements of the set is N and each set element is either in the range [0, X] or is an odd power of 2. If it is not possible to find such a size of the set then print "-1". Examples: Input: N = 11, X = 2Output: 3Explanation: The
7 min read
Highest power of a number that divides other number | Set - 2
Given two numbers N and M(M &gt; 1), the task is to find the highest power of M that divides N. Examples: Input: N = 12, M = 2Output: 2Explanation: The powers of 2 which divide 12 are 1 and 2 (21 = 2 and 22 = 4 which both divide 12). The higher power is 2, hence consider 2. Input: N = 500, M = 5Output: 3. Naive and Bit Manipulation Approach: The na
5 min read
Power Set in Lexicographic order
This article is about generating Power set in lexicographical order. Examples : Input : abcOutput : a ab abc ac b bc cThe idea is to sort array first. After sorting, one by one fix characters and recursively generates all subsets starting from them. After every recursive call, we remove last character so that next permutation can be generated. Impl
9 min read
Number of pairs whose sum is a power of 2 | Set 2
Given an array arr[] consisting of N integers, the task is to count the maximum number of pairs (arr[i], arr[j]) such that arr[i] + arr[j] is a power of 2. Examples: Input: arr[] = {1, -1, 2, 3}Output: 5Explanation: (1, 1), (2, 2), (1, 3), (-1, 3), (-1, 2) are the valid pairs whose sum is power of 2. Input: arr[] = {1, 1, 1}Output: 6 Naive Approach
9 min read
Print all possible strings that can be made by placing spaces using Power Set
Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them Examples : Input : str[] = "ABC" Output : ABC AB C A BC A B C Input : str[] = "ABCD" Output : ABCD A BCD AB CD A B CD ABC D A BC D AB C D A B C DRecommended: Please solve it on “PRACTICE ” first, before moving on to the solution. I
4 min read
Recursive program to generate power set
Given a set represented as a string, write a recursive code to print all subsets of it. The subsets can be printed in any order. Examples: Input : set = "abc"Output : { "", "a", "b", "c", "ab", "ac", "bc", "abc"} Input : set = "abcd"Output : { "", "a" ,"ab" ,"abc" ,"abcd", "abd" ,"ac" ,"acd", "ad" ,"b", "bc" ,"bcd" ,"bd" ,"c" ,"cd" ,"d" } Using Pic
12 min read
Compute modulus division by a power-of-2-number
Compute n modulo d without division(/) and modulo(%) operators, where d is a power of 2 number. Input: 6 4 Output: 2 Explanation: As 6%4 = 2 Input: 12 8 Output: 4 Explanation: As 12%8 = 4 Input: 10 2 Output: 0 Explanation:As 10%2 = 0 Let ith bit from right is set in d. For getting n modulus d, we just need to return 0 to i-1 (from right) bits of n
6 min read
Write you own Power without using multiplication(*) and division(/) operators
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 // C++ code fo
13 min read
Find operations for Array Divisibility by Power of 2
Given an array of size n, the task is to find the minimum number of operations required in the array such that the product of all array elements is divisible by nth power of 2. In one operation, you can select any index i and multiply ai by i, you can perform an operation on a particular index at most 1 time. (Follow 1-based indexing) Examples: Inp
12 min read
Smallest perfect power of 2 greater than n (without using arithmetic operators)
Given a non-negative integer n. The problem is to find the smallest perfect power of 2 which is greater than n without using the arithmetic operators.Examples : Input : n = 10 Output : 16 Input : n = 128 Output : 256 Algorithm : C/C++ Code // C++ implementation of smallest perfect power // of 2 greater than n #include &lt;bits/stdc++.h&gt; using na
4 min read
Breaking a number such that first part is integral division of second by a power of 10
Given a very large number N, we need to count the total ways such that if we divide the number into two parts a and b, the first part a can be obtained by integral division of second b by some power p of 10 and p&gt;=0. 1 &lt;= No of digits in N &lt;= [Tex]10^5 [/Tex]. Examples: Input : 220 Output : 1 220 can be divided as a = 2 and b = 20 such tha
6 min read
Check if n is divisible by power of 2 without using arithmetic operators
Given two positive integers n and m. The problem is to check whether n is divisible by 2m or not without using arithmetic operators. Examples: Input : n = 8, m = 2 Output : Yes Input : n = 14, m = 3 Output : No Approach: If a number is divisible by 2 then it has its least significant bit (LSB) set to 0, if divisible by 4 then two LSB's set to 0, if
4 min read
Multiplication with a power of 2
Given two numbers x and n, we need to multiply x with 2nExamples : Input : x = 25, n = 3 Output : 200 25 multiplied by 2 raised to power 3 is 200. Input : x = 70, n = 2 Output : 280 A simple solution is to compute n-th power of 2 and then multiply with x. C/C++ Code // Simple C/C++ program // to compute x * (2^n) #include &lt;bits/stdc++.h&gt; usin
5 min read
Find unit digit of x raised to power y
Given two numbers x and y, find unit digit of xy. Examples : Input : x = 2, y = 1 Output : 2 Explanation 2^1 = 2 so units digit is 2. Input : x = 4, y = 2 Output : 6 Explanation 4^2 = 16 so units digit is 6. Method 1 (Simple) Compute value of xy and find its last digit. This method causes overflow for slightly larger values of x and y.Method 2 (Eff
11 min read
Sum of fourth power of first n even natural numbers
Write a program to find the sum of fourth power of first n even natural numbers. 24 + 44 + 64 + 84 + 104 +.........+2n4 Examples: Input: 3Output: 156824 +44 +64 = 1568 Input: 6Output: 3640024 + 44 + 64 + 84 + 104 + 124 Naive Approach :- In this Simple finding the fourth powers of the first n even natural numbers is iterate a loop from 1 to n time.
7 min read
Power of a lens
Write a program to determine the power of a lens . Power of a lens is its ability to bend light . For a convex lens, the converging ability is defined by power and in a concave lens, the diverging ability . The diopter ( D ) is the unit of measuring power of a lens . The power is defined as the reciprocal of the focal length in meters .D = ( 1 / F
3 min read
Writing power function for large numbers
We have given two numbers x and n which are base and exponent respectively. Write a function to compute x^n where 1 &lt;= x, n &lt;= 10000 and overflow may happenExamples: Input : x = 5, n = 20 Output : 95367431640625 Input : x = 2, n = 100 Output : 1267650600228229401496703205376 In the above example, 2^100 has 31 digits and it is not possible to
11 min read
Pairs such that one is a power multiple of other
You are given an array A[] of n-elements and a positive integer k(other than 1). Now you have find the number of pairs Ai, Aj such that Ai = Aj*(kx) where x is an integer. Given that (k?1). Note: (Ai, Aj) and (Aj, Ai) must be count once. Examples : Input : A[] = {3, 6, 4, 2}, k = 2 Output : 2 Explanation : We have only two pairs (4, 2) and (3, 6) I
6 min read
Find value of y mod (2 raised to power x)
Given two positive integer x and y. we have to find the value of y mod 2x. That is remainder when y is divided by 2x. Examples: Input : x = 3, y = 14 Output : 6 Explanation : 14 % 23 = 14 % 8 = 6. Input : x = 4, y = 14 Output : 14 Explanation : 14 % 24 = 14 % 16 = 14. To solve this question we can use pow() and modulo operator and can easily find t
7 min read
Number of digits in 2 raised to power n
Let n be any power raised to base 2 i.e 2n. We are given the number n and our task is to find out the number of digits contained in the number 2n.Examples: Input : n = 5 Output : 2 Explanation : 2n = 32, which has only 2 digits. Input : n = 10 Output : 4 Explanation : 2n = 1024, which has only 4 digits. We can write 2n using logarithms as: 2n = 10n
5 min read
Perfect power (1, 4, 8, 9, 16, 25, 27, ...)
A perfect power is a number that can be expressed as power of another positive integer. Given a number n, find count of numbers from 1 to n that are of type xy where x &gt;= 1 and y &gt; 1Examples : Input : n = 10 Output : 4 1 4 8 and 9 are the numbers that are of form x ^ y where x &gt; 0 and y &gt; 1 Input : n = 50 Output : 10 A simple solution i
10 min read
Article Tags :
Practice Tags :