
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 Smaller Than or Equal to N 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
Advertisements