每 30 頭奶牛的天課是一歲的母牛,每 40 頭奶牛的天課是兩歲的母牛。
例子:
30-39 頭奶牛 -> 天課:1 頭一歲的奶牛
40-49 頭奶牛 -> zakat:1 頭兩歲的母牛
50-59 頭奶牛 -> zakat:1 頭兩歲的母牛
60-69 頭奶牛 -> zakat:2 頭一歲的奶牛
120-129 頭奶牛 -> zakat:3 頭兩歲的母牛或 4 頭一歲的奶牛
解釋:
30-39 類別:30 組合:30
30-49 類別:40 組合:40
50-59 類別:50 組合:40
60-69 類別:60 組合:30 30
120-129類別:120組合:40 40 40 OR 30 30 30 30
類別明確。只能使用數字 30 或 40 進行組合。根據組合計算 zakat。
#include <iostream>
#include <cmath>
int main()
{
int cows=67;
int category=cows-cows%10;
if(30==category)
std::cout<<"1 cow of one years old";
if(40==category)
std::cout<<"1 female cow of two years old";
if(50==category)
std::cout<<"1 female cow of two years old";
if(30 30==category)
std::cout<<"2 cows of one years old";
if(30 30 30 30==category||40 40 40==category)
std::cout<<"4 cows of one years old OR 3 female cows of two years old";
return 0;
}
你知道如何制作演算法來制作適用于大量數字的組合嗎?程式應根據組合列印 zakat。
uj5u.com熱心網友回復:
考慮一些奶牛,N。
最大二年母牛數量(簡稱V2)為地板(N/40)。因此,您的 zakat 可能有許多 V2,范圍從 0 到 floor(N/40),這使得 N-40*V2 奶牛沒有十一奉獻。這些顯然需要 floor((N-40*V2)/30) V1 來完成 zakat。
偽代碼:
N := number of cows
MV2 := floor(N/40)
out 'Possible zakat due:'
loop i from 0 to MV2:
V1 := floor((N-40*i)/30)
out i, ' female cows of 2 years, ', V1, ' cows of 1 year'
end
您可以使演算法復雜化,以確保當有多個組合時,只接受具有最少未十一奉獻的奶牛的組合。
例如,如果您有 60 頭奶牛,則基本演算法將產生 0 到 1 頭奶牛,每兩年:
V2=0, 60 cows remain, V1=2, untithed = 0
V2=1, 20 cows remain, V1=0, untithed = 20
在這種情況下,(1, 0) 解是作弊,必須丟棄。有 112 頭奶牛:
V2=0, 112 cows remain, V1=3, untithed = 22
V2=1, 72 cows remain, V1=2, untithed = 12
V2=2, 32 cows remain, V1=1, untithed = 2
在這里,最接近的解決方案是 2 頭奶牛 2 年,1 頭奶牛 1 年。
在 C 中:
#include <math.h>
#include <stdio.h>
int main() {
int cows;
printf("Enter number of cows: ");
scanf("%d", &cows);
int category = cows - cows % 10;
int N, v2, mx, b1, b2, un, i;
for (N = 0; N <= cows; N = 10) {
v2 = floor(N / 40);
mx = 40;
b2 = 0;
b1 = 0;
for (i = 0; i <= v2; i ) {
int j = floor((N - 40 * i) / 30);
un = N - 40 * i - 30 * j;
if (un <= mx) {
b2 = i;
b1 = j;
mx = un;
}
}
un = N - 40 * b2 - 30 * b1;
if (N == category) {
printf("For %d cows, the zakat is:\n", cows);
if (cows < 30)
printf("0 cows");
if (b1)
printf("%d one years old cows\n", b1);
if (b2)
printf("%d two years old female cows\n", b2);
}
}
}
輸出:
Enter number of cows: 140
For 140 cows, the zakat is:
2 one years old cows
2 two years old female cows
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/468470.html
上一篇:以索引形式回傳結果的二分搜索
下一篇:深度優先搜索找到二叉樹的最大深度