Minimum numbers which is smaller than or equal to N and with sum S in C++

C++Server Side ProgrammingProgramming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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

Live Demo

#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
Updated on 23-Dec-2019 06:00:36