This example computes the permanent of a square integer matrix in two ways:
naive_permanentdirectly enumerates all column permutations.ryser_permanentuses Ryser's formula with Gray-code subset traversal.
| Algorithm | Cases examined | Time | Extra space |
|---|---|---|---|
| Naive | n! permutations |
O(n * n!) |
O(n) |
| Ryser | 2^n subsets |
O(n * 2^n) |
O(n) |
Both are exponential, but 2^n grows much more slowly than n!. For example:
| Matrix size | Naive permutations | Ryser subsets |
|---|---|---|
| 4 | 24 | 16 |
| 8 | 40,320 | 256 |
| 12 | 479,001,600 | 4,096 |
| 20 | 2,432,902,008,176,640,000 | 1,048,576 |
Run the example:
cargo runThe program compares both implementations on an 8 x 8 all-ones matrix. Its
permanent is 8! = 40,320. Example output (timings vary by machine and build):
Naive: result = 40320, time = 9.1ms
Ryser: result = 40320, time = 84.2us
Naive examines 8! = 40,320 permutations.
Ryser examines 2^8 - 1 = 255 non-empty subsets.
Run the tests:
cargo testUse cargo run --release for a meaningful timing comparison. The test suite
also checks that both algorithms return the same result for several matrices.