使用C++计算力量P可以杀死的最大人数
给定任务是找到使用力量P可以杀死的最大人数。考虑一个包含无限人数的行,每个人都有从1开始的索引号。
第s个人的力量用s2表示。杀死一个具有s力量的人后,你的力量也会减少s。
让我们用一个例子来理解我们必须做什么:
输入
P = 20
输出
3
解释
Strength of 1st person = 1 * 1 = 1 < 20, therefore 1st person can be killed. Remaining strength = P – 1 = 20 – 1 = 19 Strength of 2nd person = 2 * 2 = 4 < 19, therefore 2nd person can be killed. Remaining strength = P – 4 = 19 – 4 = 15 Strength of 3rd person = 3 * 3 = 9 < 15, therefore 3rd person can be killed. Remaining strength = P – 9 = 15 – 9 = 6 Strength of 4th person = 4 * 4 = 16 > 6, therefore 4th person cannot be killed. Output = 3
输入
30
输出
4
下面程序中使用的方法如下
在main()函数中,初始化类型为int的P = 30,因为它将存储力量,并将其传递到Max()函数。
在Max()函数中,初始化类型为int的s = 0和P = 0。
从j = 1循环到j * j <= P
设置s = s + (j * j),如果s <= P,则将ans加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;
}
//main function
int main(){
//Strength
int P = 30;
cout << “Maximum number of people that can be killed with strength P are: ”<<Max(P);
return 0;
}输出
Maximum number of people that can be killed with strength P are: 4
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP