2013-02-08 91 views
1

我製作了一系列素數的數字 - 這應該是難題!但是,爲了創建相同數量的因子列表,主要因素需要以各種可能的方式進行組合。我正在努力用php做的事情。PHP陣列產品組合

例如,我有數組:

2 
2 
2 
3 
3 
41 
53 

...爲號156456;把它們全部放在一起,然後回到數字。我需要做的是將所有的二重奏一起乘以2x2,2x3,2x53等,然後將所有的三元組合在一起,等等,直到我最終將六個七個塊一起相乘。

正如你所看到的,這將給與一個非常大的陣列,所有的因數,4,6,8,9,12等與許多重複。我似乎無法從我上面的數組中得到這個我想要的除數。這是數組中每個元素的每種可能組合的乘法,是否有一個php函數,迄今爲止我的搜索沒有結果?

+0

使用[array_unique](http://php.net/array_unique)刪除重複項 – MarcDefiant 2013-02-08 12:19:03

+0

沒有這樣的官方PHP函數。你將不得不編寫你自己的算法。或者你可以嘗試找到一個開源的實現。 – 2013-02-08 12:19:06

+0

任何人都可以給我一個點在正確的方向,我的猜測是,我發現有多少元素在數組中,然後循環通過,所以對於上述我會有6個循環,我帶來了二重奏,然後三胞胎等,但仍不知道如何實施 – user1967034 2013-02-08 12:23:10

回答

1

閱讀本頁:http://mathcentral.uregina.ca/QQ/database/QQ.02.06/joe1.html,我試圖建立一些可能的工作,它可能不是最有效的解決方案,它也限於在32位系統上的count($primes) <= 32。如果您需要更多,隨意使用Bitset

$primes = Array(2, 2, 2, 3, 3, 41, 53); 
$num_primes = count($primes); // 7, if this is over 32, it won't work on 32bit systems 
$divisors = Array(); 

// number of possible combinations 
$limit = pow(2, $num_primes) - 1; // 127 

// count a number up and use the binary 
// representation to say which index is 
// part of the current divisor 
for($number = 0; $number <= $limit; $number++) { 
    $divisor = 1; 
    // only multiply activated bits in $number to the divisor 
    for($i = 0; $i < $num_primes; $i++) { 
     $divisor *= ($number >> $i) & 1 ? $primes[$i] : 1; 
    } 
    $divisors[] = $divisor; 
} 

echo implode(", ", array_unique($divisors)); 

這將導致到以下因數:

1, 2, 4, 8, 3, 6, 12, 24, 9, 18, 36, 72, 41, 82, 164, 328, 123, 246, 492, 
984, 369, 738, 1476, 2952, 53, 106, 212, 424, 159, 318, 636, 1272, 477, 
954, 1908, 3816, 2173, 4346, 8692, 17384, 6519, 13038, 26076, 52152, 19557, 
39114, 78228, 156456 

找到你需要在每一個可能的相互乘以每一個素因子所有分頻器組合。爲此,我計算可能的組合數($limit)。如果你現在算數達此限制二進制表示看起來是這樣的:

7 bit 
<-----> 
0000000 0 
0000001 1 
0000010 2 
0000011 3 
0000100 4 
0000101 5 
0000110 6 
0000111 7 
0001000 8 
0001001 9 
... 
1111110 126 
1111111 127 

$number目前的二進制表示法表示的$primes指標來計算當前$divisor。爲了更好地展示這一點,我們假設$number = 5,它是二進制的0000101。並且$divisor的計算將是2 * 1 * 2 * 1 * 1 * 1 * 1 = 4。只有第一位和第三位被設置,因此只有數組中的第一個和第三個元素用於計算。

我希望這可以使它更清晰一點。

+0

我能說什麼,完美。我會看看第一個數字是多於32個素數因子,但是它很好地回答了這個問題。謝謝。 – user1967034 2013-02-08 13:20:52

+0

...實際上它必須是2^33這是8,589,934,592,這是我需要去的高度,問題解決了。 – user1967034 2013-02-08 13:24:37