ภารกิจคือการหาจำนวนคนสูงสุดที่สามารถฆ่าได้ด้วยพลัง P พิจารณาแถวคนที่มีจำนวนไม่จำกัด แต่ละคนมีหมายเลขดัชนีเริ่มจาก 1
พลังของคนที่ s คือ s² หลังจากฆ่าคนที่มีพลัง s พลังของคุณก็ลดลง s
ตัวอย่าง
อินพุต
P = 20
เอาต์พุต
3
คำอธิบาย
พลังคนที่ 1 = 1×1 = 1 < 20 ฆ่าได้ เหลือ P = 20-1 = 19 พลังคนที่ 2 = 2×2 = 4 < 19 ฆ่าได้ เหลือ P = 19-4 = 15 พลังคนที่ 3 = 3×3 = 9 < 15 ฆ่าได้ เหลือ P = 15-9 = 6 พลังคนที่ 4 = 4×4 = 16 > 6 ฆ่าไม่ได้ Output = 3
อินพุต
30
เอาต์พุต
4
แนวทางที่ใช้ในโปรแกรมด้านล่าง
- ใน main() เริ่มต้น P = 30 แบบ int ส่งเข้า Max()
- ใน Max() เริ่มต้น s = 0, ans = 0
- ลูป j = 1 ถึง j*j <= P
- s = s + (j*j) ถ้า s <= P เพิ่ม ans มิฉะนั้น break
- คืนค่า 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 strength P are: " << Max(P);
return 0;
}
เอาต์พุต
Maximum number of people that can be killed with strength P are: 4