2025-09-30 01:52:52 +00:00
/ *
Copyright © 2025 filifa
This program is free software : you can redistribute it and / or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with this program . If not , see < http : //www.gnu.org/licenses/>.
* /
package lib
import (
"math/big"
)
// given a slice where vals[i] = p_{k-1}(i) for a given k, nextPartition updates the slice so vals[i] = p_k(i) using the property that p_k(n) = p_k(n-k) + p_{k-1}(n)
func nextPartition ( k int , vals [ ] * big . Int ) {
for i := 1 ; i < len ( vals ) ; i ++ {
if i - k >= 0 {
vals [ i ] . Add ( vals [ i ] , vals [ i - k ] )
}
}
}
2025-10-01 03:58:28 +00:00
/ *
Partitions computes the number of ways to add to n with k or fewer terms .
* /
2025-09-30 01:52:52 +00:00
func Partitions ( n , k int ) * big . Int {
if n < 0 {
return big . NewInt ( 0 )
}
if k > n {
k = n
}
vals := make ( [ ] * big . Int , n + 1 )
for i := range vals {
vals [ i ] = big . NewInt ( 0 )
}
vals [ 0 ] = big . NewInt ( 1 )
for i := 1 ; i <= k ; i ++ {
nextPartition ( i , vals )
}
return vals [ n ]
}