
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Minimum numbers which is smaller than or equal to N and with sum S in C++
Problem statement
Given N numbers from 1 to N and a number S. The task is to print the minimum number of numbers that sum up to give S
Example
If n = 7 and s = 10 then minimum 2 numbers are required
(9, 1) (8, 2) (7, 3) (6, 4)
Algorithm
Answer can be calculated using below formula (S/N) + 1 if { S %N > 0}
Example
#include <bits/stdc++.h> using namespace std; int getMinNumbers(int n, int s) { return s % n ? s / n + 1 : s / 2; } int main() { int n = 7; int s = 10; cout << "Required minimum numbers = " << getMinNumbers(n, s) << endl; return 0; }
When you compile and execute above program. It generates following output
Output
Required minimum numbers = 2
- Related Articles
- Count numbers (smaller than or equal to N) with given digit sum in C++
- Euler’s Totient function for all numbers smaller than or equal to n in java
- Largest number smaller than or equal to N divisible by K in C++
- Print all Jumping Numbers smaller than or equal to a given value in C++
- Count numbers whose XOR with N is equal to OR with N in C++
- Find all factorial numbers less than or equal to n in C++
- Print all prime numbers less than or equal to N in C++
- Print all Semi-Prime Numbers less than or equal to N in C++
- First element greater than or equal to X in prefix sum of N numbers using Binary Lifting in C++
- Minimum number of power terms with sum equal to n using C++.
- Cube Free Numbers smaller than n
- Count of Binary Digit numbers smaller than N in C++
- Print triplets with sum less than or equal to k in C Program
- Find maximum product of digits among numbers less than or equal to N in C++
- Count elements smaller than or equal to x in a sorted matrix in C++

Advertisements