RosettaCodeData/Task/Partition-an-integer-x-into-n-primes/FreeBASIC/partition-an-integer-x-into-n-primes.basic
2024-10-16 18:07:41 -07:00

45 lines
1.2 KiB
Text

'#include "isprime.bas"
Function getPrime(idx As Integer) As Integer
Dim As Integer count = 0
Dim As Integer num = 1
Do
num += 1
If isPrime(num) Then count += 1
Loop Until count = idx
Return num
End Function
Function partition(v As Integer, n As Integer, idx As Integer = 0) As String
If n = 1 Then Return Iif(isPrime(v), Str(v), "0")
Do
idx += 1
Dim As Integer np = getPrime(idx)
If np >= Int(v / 2) Then Exit Do
Dim As String res = partition(v - np, n - 1, idx)
If res <> "0" Then Return Str(np) & " + " & res
Loop
Return "0"
End Function
Dim tests(10, 2) As Integer
tests(1, 1) = 99809: tests(1, 2) = 1
tests(2, 1) = 18: tests(2, 2) = 2
tests(3, 1) = 19: tests(3, 2) = 3
tests(4, 1) = 20: tests(4, 2) = 4
tests(5, 1) = 2017: tests(5, 2) = 24
tests(6, 1) = 22699: tests(6, 2) = 1
tests(7, 1) = 22699: tests(7, 2) = 2
tests(8, 1) = 22699: tests(8, 2) = 3
tests(9, 1) = 22699: tests(9, 2) = 4
tests(10, 1) = 40355: tests(10, 2) = 3
For i As Integer = 1 To 10
Dim As Integer v = tests(i, 1)
Dim As Integer n = tests(i, 2)
Dim As String res = partition(v, n)
Print "Partition "; v; " into "; n; " primes: "; Iif(res = "0", "not possible", res)
Next
Sleep