给定任务是找到可以用力量P杀死的最大人数。考虑一行中有无限人数,并且每个人的索引号都从1开始。
的强度š个人用s表示2。杀死具有s力量的人后,您的力量也会降低s。
现在让我们使用示例了解我们必须做的事情-
P = 20
输出结果
3
强度 of 1st person = 1 * 1 = 1 < 20, therefore 1st person can be killed. Remaining 强度 = P – 1 = 20 – 1 = 19 强度 of 2nd person = 2 * 2 = 4 < 19, therefore 2nd person can be killed. Remaining 强度 = P – 4 = 19 – 4 = 15 强度 of 3rd person = 3 * 3 = 9 < 15, therefore 3rd person can be killed. Remaining 强度 = P – 9 = 15 – 9 = 6 强度 of 4th person = 4 * 4 = 16 > 6, therefore 4th person cannot be killed. Output = 3
30
输出结果
4
在main()
函数中初始化int类型的P = 30,因为它将存储强度并将其传递给Max()
函数。
在Max()
函数中初始化s = 0和P = 0均为int类型。
从j = 1循环到j * j <= P
放s = s +(j * j),如果s <= P将an加1,否则中断;
返回ans。
#include <bits/stdc++.h> using namespace std; int Max(int P){ int s = 0, ans = 0; for (int j = 1; j * j <= P; j++){ s = s + (j * j); if (s <= P) ans++; else break; } return ans; } //主要功能 int main(){ //强度 int P = 30; cout << “Maximum number of people that can be killed with 强度 P are: ”<<Max(P); return 0; }
输出结果
Maximum number of people that can be killed with 强度 P are: 4