Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

จำนวนคนสูงสุดที่สามารถฆ่าได้ด้วยความแรง P ใน C++


มอบหมายให้หาจำนวนคนสูงสุดที่สามารถฆ่าได้ด้วยความแรง P. พิจารณาแถวที่มีคนไม่สิ้นสุดและแต่ละคนมีหมายเลขดัชนีเริ่มต้นจาก 1

ความแข็งแกร่งของ s th บุคคลนั้นแสดงโดย s 2 . หลังจากฆ่าคนที่มีความแข็งแกร่งแล้ว ความแข็งแกร่งของคุณก็ลดลงเช่นกัน

ตอนนี้มาทำความเข้าใจสิ่งที่เราต้องทำโดยใช้ตัวอย่าง -

อินพุต

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() ให้กำหนดค่าเริ่มต้น P =30 ของประเภท int เนื่องจากจะเก็บค่าความแรงและส่งผ่านไปยังฟังก์ชัน Max()

  • ในฟังก์ชัน Max() เริ่มต้น s =0 และ P =0 ทั้งสองประเภท int

  • วนจาก j =1 ถึง j * j <=P

  • ใส่ s =s + (j * j) และถ้า s <=P เพิ่ม 1 ใน ans มิฉะนั้นจะแตก;

  • กลับ 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