我正在嘗試制作一個程式,該程式將計算物件體積的長度、高度和寬度的所有多種組合。
我創建了一些回圈來遍歷所有可能的組合,但我不知道如何防止出現倍數?例如,如果已經找到了 1x1x2,我不想計算 1x2x1。到目前為止,這是我的代碼:
#include <stdio.h>
#include <math.h>
int main(){
int v, m = 0, k = 0;
scanf("%d", &v); // a is length b is width c is height and v is volume
for(int a=1;a<=v;a ){
for(int b=1;b<v;b ){
for(int c=1;c<v;c ){
m = a*b*c;
if(m == v){
k = k 1; //k is the number of combinations
}
}
}
}
printf("The number of combinations was: %d", k);
return 0;
}
uj5u.com熱心網友回復:
你剛剛在評論中說你不想真正經歷所有這些組合;你只想要他們的人數。
這更容易,因為它是基本的組合學:這只是帶有重復的k 組合的數量;這種組合的數量是多集系數,可以用二項式系數表示,易于計算,由

這里,n 是可供選擇的元素數(這就是v你的情況!),k 是你選擇的元素數,所以是 3。
所以,您需要做的就是撰寫一個 C 函式,它接受兩個數字 n 和 k,并計算 (n k-1 k)!/ (n!·(n k-1-k)!)。我相信你可以寫一個教師功能。
uj5u.com熱心網友回復:
注意問題基本上是一個整數的因式分解,這樣可以節省很多迭代:
int combinations(int volume)
{
int k = 0;
for ( int a = 1; a <= volume / a; a )
{ // ^^^^^^^^^^^^^^^ Up to the square root of volume
if ( volume % a == 0 )
{ // ^^^^^^^^^^^^^^^ Consider only the factors
const int area = volume / a;
for( int b = a; b <= area / b; b )
{
if ( area % b == 0 )
{
const int length = area / b;
printf("%d = %d * %d * %d\n", a * b * length, a, b, length);
k;
}
}
}
}
return k;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362950.html
