C++ 中求和为 S 且小于或等于 N 的最小数字

c++server side programmingprogramming

问题描述

给定 N 个从 1 到 N 的数字和一个数字 S。任务是输出使和为 S 的最小数字个数。

示例

如果 n = 7 且 s = 10,则至少需要 2 个数字

(9, 1)
(8, 2)
(7, 3)
(6, 4)

算法

答案可以使用以下公式计算
(S/N) + 1 if { S %N > 0}

示例

#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 << "所需的最小数量 = " <<
   getMinNumbers(n, s) << endl;
   return 0;
}

编译并执行上述程序,将生成以下输出

输出

所需的最小数量 = 2

相关文章