Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import gmp, random, strutils
- const terms = 3
- proc `$`(n: mpz_t): string =
- var cstr: cstring
- cstr = mpz_get_str(cstr, 10, n)
- return $cstr
- proc getRandomMpzArr(): array[terms, mpz_t] =
- for i in 0..<terms:
- mpz_init result[i]
- mpz_set_si result[i], clong.rand
- proc getExpSum(x: array[terms, mpz_t], debug = false, pow = 3): mpz_t =
- # Pretty-print the calculation to be performed (debug mode):
- if debug:
- var outStr: seq[string]
- for i in 0..<terms:
- outStr.add "$1**$2" % [$x[i], $pow]
- echo "(" & outStr.join(" + ") & ")"
- # Raise to exponent:
- var powX: array[terms, mpz_t]
- for i in 0..<terms:
- mpz_pow_ui powX[i], x[i], pow.culong
- if debug:
- echo "==\n(" & powX.join(" + ") & ")"
- # Calculate sum:
- var sum: mpz_t
- mpz_init sum
- for i in 0..<terms:
- mpz_add sum, sum, powX[i]
- if debug:
- echo "==\n$1\n" % $sum
- return sum
- proc searchForTarget(loopsMax = int.high, targetMax = 2_000_000_000) =
- ## Tries random number combinations until their sum is <targetMax.
- randomize 19811019
- var mpzTargetMax: mpz_t
- mpz_init mpzTargetMax
- mpz_set_si mpzTargetMax, targetMax
- var loopCount = 0
- while loopCount < loopsMax:
- inc loopCount
- if loopCount %% 1_000_000 == 0:
- echo "Tried $1 combinations..." % $loopCount
- let x = getRandomMpzArr()
- let sum = getExpSum(x)
- let cmp = mpz_cmpabs(sum, mpzTargetMax)
- if cmp < 0:
- echo "SUCCESS!!!"
- discard getExpSum(x, true)
- quit 1
- when isMainModule:
- searchForTarget()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement