使用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