給定繁殖率的C++中,a、b和c在n秒後的數量


給定三個數字'a'、'b'和'c'作為輸入。目標是在n秒後找到'a'、'b'和'c'的數量/值,其繁殖率為:

  • 每隔2秒,每個a都會變成b
  • 每隔5秒,每個b都會變成c
  • 每隔12秒,每個c都會變成2個a。

讓我們用例子來理解。

例如

輸入 - n_seconds = 62  a = 1 b = 1 c = 1

輸出 - 給定繁殖率下,n秒後a的數量為:0

給定繁殖率下,n秒後b的數量為:33

給定繁殖率下,n秒後c的數量為:1

解釋 - 60秒後,a將為32,b = 0,c = 0。

再過2秒,所有b都將變成c,c=1。所有a變成b,b=33。

輸入 - n_seconds = 20  a = 1 b = 1 c = 1

輸出 - 給定繁殖率下,n秒後a的數量為:0

給定繁殖率下,n秒後b的數量為:0

給定繁殖率下,n秒後c的數量為:6

解釋

1秒:-  a=1,b=1,c=1

2秒:-  a=0,b=2(1+1) ,c=1          → 2秒後a變為b

4秒:-  a=0,b=2 ,c=1                  → 2秒後a變為b

5秒:-  a=0,b=0 ,c=3 (1+2)        → 5秒後b變為c

6秒:-  a=0,b=0 ,c=3                  → 2秒後a變為b

8秒:-  a=0,b=0 ,c=3                  → 2秒後a變為b

10秒:-  a=0,b=0 ,c=3               → 5秒後b變為c

12秒:-  a=6 (0+2*3),b=0 ,c=0     → 12秒後c變為2a

14秒:-  a=0,b=6(0+6) ,c=0          → 2秒後a變為b

15秒:-  a=0,b=0 ,c=6(0+6)         → 5秒後b變為c

16秒:-  a=0,b=0 ,c=6                  → 2秒後a變為b

18秒:-  a=0,b=0 ,c=6                  → 2秒後a變為b

20秒:-  a=0,b=0 ,c=6                 → 5秒後b變為c

下面程式中使用的方案如下

秒數的最小公倍數為60(2、5、12)。因此,每隔60秒,a、b和c的變化將是

60秒→ a= 32,b=0,c=0

120秒→ a= 32*32 ,b=0,c=0

180秒→ a= 32*32*32 ,b=0,c=0。

對於以60為倍數的秒數,按上述方法計算a的值。對於非倍數,計算最接近的倍數temp,然後從temp+1遍歷到輸入秒數,並使用模2、5或12進行計算。

  • 將數字a、b和c作為輸入。
  • 將n_seconds作為以秒為單位的時間。
  • 函式reproduction_rate(int n_seconds, int a, int b, int c)獲取所有引數,並列印給定繁殖率下n秒後a、b和c的數量。
  • 將temp = n_seconds / 60作為n_seonds以下的60的倍數。
  • 根據公式計算a = (int)pow(32, temp)。( atemp )
  • 現在將temp更新為60 * temp,以獲得小於或等於n_seconds的最接近的60的倍數。
  • 現在使用for迴圈從i=temp+1遍歷到i=n_seconds。
  • 如果數字i是2的倍數,則透過新增a並使a為0來更新b。
  • 如果數字i是5的倍數,則透過新增b並使b為0來更新c。
  • 如果數字i是12的倍數,則透過新增2c並使c為0來更新a。
  • 在for迴圈結束時,列印a、b和c的最終值。

示例

線上演示

#include <bits/stdc++.h>
using namespace std;

void reproduction_rate(int n_seconds, int a, int b, int c) {
   int temp = n_seconds / 60;
   a = (int) pow(32, temp);
   temp = 60 * temp;

   for (int i = temp + 1; i <= n_seconds; i++) {
      if (i % 2 == 0) {
         b = b + a;
         a = 0;
      }
      if (i % 5 == 0) {
         c = c + b;
         b = 0;
      }
      if (i % 12 == 0) {
         a = a + (2 * c);
         c = 0;
      }
   }
   cout << "Count of a after n seconds for given reproduction rate is: " << a << "\n";
   cout << "Count of b after n seconds for given reproduction rate is: " << b << "\n";
   cout << "Count of c after n seconds for given reproduction rate is: " << c;
}
int main() {
   int n_seconds = 72;
   int a = 2;
   int b = 1;
   int c = 1;
   reproduction_rate(n_seconds, a, b, c);
   return 0;
}

如果我們執行以上程式碼,它將生成以下輸出:

輸出

Count of a after n seconds for given reproduction rate is: 68
Count of b after n seconds for given reproduction rate is: 0

Count of c after n seconds for given reproduction rate is: 0

更新於: 2021年1月29日

78 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.