- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Minimum numbers needed to express every integer below N as a sum in C++

## Problem statement

We have an integer N. We need to express N as a sum of K integers such that by adding some or all of these integers we can get all the numbers in the range 1 to N. The task is to find minimum value of K

## Example

If N = 8 then final answer i.e. K would be 3

If we take integers 1, 2, 3, and 4 then adding some or all of these groups we can get all number in the range 1 to N

e.g. 1 = 1 2 = 2 3 = 3 4 = 4 5 = 1 + 5 6 = 4 + 2 7 = 4 + 3 8 = 1 + 3 + 4

## Algorithm

Count number of bits from given integer

## Example

#include <bits/stdc++.h> using namespace std; int getMinNumbers(int n) { int cnt = 0; while (n) { ++cnt; n = n >> 1; } return cnt; } int main() { int n = 8; cout << "Minimum required numbers = " <<getMinNumbers(n) << endl; return 0; }

When you compile and execute above program. It generates following output

## Output

Minimum required numbers = 4

- Related Questions & Answers
- Minimum number of palindromes required to express N as a sum using C++.
- Count ways to express a number as sum of consecutive numbers in C++
- Express an odd number as sum of prime numbers in C++
- Sum of the multiples of two numbers below N in C++
- Count ways to express ‘n’ as sum of odd integers in C++
- C++ program to count minimum number of binary digit numbers needed to represent n
- Count ways to express a number as sum of powers in C++
- Count of different ways to express N as the sum of 1, 3 and 4 in C++
- Minimum number of letters needed to make a total of n in C++.
- Represent a Number as Sum of Minimum Possible Pseudo-Binary Numbers in C++
- Maximum sum of distinct numbers with LCM as N in C++
- Program to express a positive integer number in words in C++
- Find a number which give minimum sum when XOR with every number of array of integer in C++
- Find ways an Integer can be expressed as sum of n-th power of unique natural numbers in C++
- C++ program to find ways an integer can be expressed as sum of n-th power of unique natural numbers

Advertisements