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
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimize difference between two sequences obtained by splitting first N powers of 2
Next article icon

Minimize subsequence multiplication to convert Array sum to be power of 2

Last Updated : 07 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array A[] of size N such that every element is a positive power of 2. In one operation, choose a non-empty subsequence of the array and multiply all the elements of the subsequence with any positive integer such that the sum of the array becomes a power of 2. The task is to minimize this operation.

Examples:

Input: S = {4, 8, 4, 32}   
Output: 
1
5 
{4}

Explanation: Choose a subsequence {4} and multiplying it by 5 
turns the array into [20, 8, 4, 32], whose sum is 64 = 26. 
Hence minimum number of operations required to make 
sum of sequence into power of 2 is 1.

Input: S = {2, 2, 4, 8}
Output: 0
Explanation: The array already has a sum 16 which is power of 2.

Approach: The problem can be solved based on the following observation:

Observations:

If the sum of sequence is already power of 2, we need 0 operations.

Otherwise, we can make do itusing exactly one operation.                                                                                                        

  • Let S be the sum of the sequence. We know that S is not a power of 2. After some number of operations, let us assume  that we achieve a sum of 2r.
  • S < 2r: This is because, in each operation we multiply some subsequence with a positive integer. This would increase the value of the elements of that subsequence and thus the overall sum.
  • This means that we have to increase S at least to 2r such that 2r−1 < S < 2r. For this, we need to add 2r − S to the sequence.
    Let M denote the smallest element of the sequence. Then 2r − S is a multiple of M.

To convert S to 2r, we can simply multiply M by (2r − (S − M)) / M. This would take only one operation and make the sum of sequence equal to a power of 2. The chosen subsequence in the operation only consists of M.

Follow the steps mentioned below to implement the idea:

  • Check if the sequence is already the power of 2, then the answer is 0.
  • Otherwise, we require only 1 operation
    • Let S be the sum of the sequence (where S is not a power of 2) and r be the smallest integer such that S < 2r. 
    • In one operation, we choose the smallest number of the sequence (M) and multiply it with X = 2r − (S − M) / M.
  • Print the element whose value is minimum in the array.

Below is the implementation of the above approach:

C++
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std;  // Function to find the minimum number // of operation, multiplier // and the subsequence void minOperation(int a[], int n) {   long sum = 0;   int idx = 0;   long min = INT_MAX;   for (int i = 0; i < n; i++) {     sum += a[i];     if (a[i] < min) {       min = a[i];       idx = i + 1;     }   }   long power = (long)(log(sum) / log(2));   if (sum == (long)pow(2, power)) {     cout<<(0)<<endl;   }   else {     cout<<(1)<<endl;     cout<<((       ((long)(pow(2, power + 1) - sum) / min)       + 1))<<endl;     cout<<(a[idx - 1])<<endl;   } }  // Driver code int main() {   int A[] = { 4, 8, 4, 32 };   int N = sizeof(A) / sizeof(A[0]);    // Function call   minOperation(A, N); }  // This code is contributed by Potta Lokesh 
Java
// Java code to implement the approach  import java.io.*; import java.util.*; class GFG {      // Function to find the minimum number     // of operation, multiplier     // and the subsequence     public static void minOperation(int a[], int n)     {         long sum = 0;         int idx = 0;         long min = Long.MAX_VALUE;         for (int i = 0; i < n; i++) {             sum += a[i];             if (a[i] < min) {                 min = a[i];                 idx = i + 1;             }         }         long power = (long)(Math.log(sum) / Math.log(2));         if (sum == (long)Math.pow(2, power)) {             System.out.println(0);         }         else {             System.out.println(1);             System.out.println((                 ((long)(Math.pow(2, power + 1) - sum) / min)                 + 1));             System.out.println(a[idx - 1]);         }     }      // Driver code     public static void main(String[] args)     {         int A[] = { 4, 8, 4, 32 };         int N = A.length;          // Function call         minOperation(A, N);     } } 
Python3
# Python code to implement the approach import math  # Function to find maximum value among all distinct ordered tuple def minOperation(a, n):     sum = 0     ind = 0     mini = 200000000000     for i in range(n):         sum += A[i]         if A[i] < mini:             mini = A[i]             ind = i+1     power = int(math.log2(sum))      if sum == pow(2, power):         print("0")     else:         print("1")         print((int(pow(2, power+1))-sum)//mini+1)         print(a[ind-1])  # Driver Code if __name__ == '__main__':     A = [4, 8, 4, 32]     N = len(A)      # Function call     minOperation(A, N)      # This code is contributed by aarohirai2616. 
C#
// C# code to implement the approach using System;  public class GFG  {      // Function to find the minimum number   // of operation, multiplier   // and the subsequence   public static void minOperation(int[] a, int n)   {     long sum = 0;     int idx = 0;     long mini = Int64.MaxValue;     for (int i = 0; i < n; i++) {       sum += a[i];       if (a[i] < mini) {         mini = a[i];         idx = i + 1;       }     }     long power = (long)(Math.Log(sum) / Math.Log(2));     if (sum == (long)Math.Pow(2, power)) {       Console.WriteLine(0);     }     else {       Console.WriteLine(1);       Console.WriteLine(         (((long)(Math.Pow(2, power + 1) - sum)           / mini)          + 1));       Console.WriteLine(a[idx - 1]);     }   }    // Driver Code   static public void Main()   {     int[] A = { 4, 8, 4, 32 };     int N = A.Length;      // Function call     minOperation(A, N);   } }  // This code is contributed by Rohit Pradhan 
JavaScript
<script>  // JavaScript code to implement the approach      // Function to find the minimum number     // of operation, multiplier     // and the subsequence     function minOperation(a, n)     {         let sum = 0;         let idx = 0;         let min = Number.MAX_VALUE;         for (let i = 0; i < n; i++) {             sum += a[i];             if (a[i] < min) {                 min = a[i];                 idx = i + 1;             }         }         let power = Math.floor(Math.log(sum) / Math.log(2));         if (sum == Math.pow(2, power)) {             document.write(0);         }         else {             document.write(1 + "<br/>");             document.write((                 Math.floor((Math.pow(2, power + 1) - sum) / min)                 + 1) + "<br/>");             document.write(a[idx - 1] + "<br/>");         }     }  // Driver Code         let A = [ 4, 8, 4, 32 ];         let N = A.length;          // Function call         minOperation(A, N);  / This code is contributed by sanjoy_62. </script> 

Output
1 5 4

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


Next Article
Minimize difference between two sequences obtained by splitting first N powers of 2
author
aarohirai2616
Improve
Article Tags :
  • Mathematical
  • Competitive Programming
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Mathematical

Similar Reads

  • Minimize subtraction of power of 2 to convert N to 0
    Given a positive integer N, the task is to find the minimum number of subtractions of power of 2 required to convert N to 0. Examples: Input: 10Output: 2Explanation: When we subtract 8 from 10 ( 10 - (2^3) = 2) then 2 will remain. After that subtract 2 from 2^0 i.e., 2 - 2^0 = 0. Hence we are doing
    9 min read
  • Minimum steps required to rearrange given array to a power sequence of 2
    Given an array arr[] consisting of N positive integers, the task is to find the minimum steps required to make the given array of integers into a sequence of powers of 2 by the following operations: Reorder the given array. It doesn't count as a step.For each step, select any index i from the array
    4 min read
  • Minimize multiply by position so that Array product is divisible by 2^K
    Given an array nums [] of size N containing positive integers and a positive integer K, the task is to find the minimum number of operations such that the array product is divisible by 2K where in each operation nums[i] is multiplied by its position (i.e. i+1). Note: Return -1 if it is not possible
    11 min read
  • Minimize difference between two sequences obtained by splitting first N powers of 2
    Given a positive even number N, the task is to split the first N powers of 2 into two equal sequences such that the absolute difference between their sum is minimized. Print the minimum difference obtained. Examples: Input: N = 2Output: 2Explanation:The sequence is {2, 4}.Only possible way to split
    5 min read
  • Minimum deletions to be done in given array such that every pair sum is a power of 2
    Given an array arr[] consisting of N integers the task is to find the minimum number of elements that should be removed, such that for every remaining element arr[i], there exists another element arr[j], (i!=j) such that the sum of arr[i] and arr[j] is a power of 2. If after any number of deletions,
    9 min read
  • Minimize operations to convert Array elements to 0s
    Given an array nums[] of length N containing non-negative integers, the task is to convert all elements from index 0 to N-2 to zero, after doing the below operations minimum number of times. In one operation select two indices i and j such that i < j and all the elements between i and j has to be
    6 min read
  • Minimum increments or decrements required to convert a sorted array into a power sequence
    Given a sorted array arr[] consisting of N positive integers, the task is to minimize the total number of increments or decrements of each array element required to convert the given array into a power sequence of any arbitrary integer X. A sequence is called a power sequence of any integer X, if an
    8 min read
  • Minimize Cost to reduce the Array to a single element by given operations
    Given an array a[] consisting of N integers and an integer K, the task is to find the minimum cost to reduce the given array to a single element by choosing any pair of consecutive array elements and replace them by (a[i] + a[i+1]) for a cost K * (a[i] + a[i+1]). Examples: Input: a[] = {1, 2, 3}, K
    15+ min read
  • Minimize Array elements to be reduced to make subsequences sum 1 to Array max possible
    Given an array a[] of positive integers. Subtract any positive integer from any number of elements of the array such that there exists every possible subsequence with sum 1 to s, where s denotes the sum of all the elements of the array. Find the minimum possible number of the array element to be sub
    6 min read
  • Count of elements to be multiplied with integers to make each pair of Array a perfect square
    Given an array arr[] containing positive integers, the task is to find the minimum number of operations to be done on the array to make every number of the array a superpower. In each operation, we can multiply any element of the array with an integer. A superpower is defined as a number in the arra
    15+ 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