Advertisement
Guest User

Untitled

a guest
Mar 13th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 1.53 KB | None | 0 0
  1. import gmp, random, strutils
  2.  
  3. const terms = 3
  4.  
  5. proc `$`(n: mpz_t): string =
  6.   var cstr: cstring
  7.   cstr = mpz_get_str(cstr, 10, n)
  8.   return $cstr
  9.  
  10. proc getRandomMpzArr(): array[terms, mpz_t] =
  11.   for i in 0..<terms:
  12.     mpz_init result[i]
  13.     mpz_set_si result[i], clong.rand
  14.  
  15. proc getExpSum(x: array[terms, mpz_t], debug = false, pow = 3): mpz_t =
  16.   # Pretty-print the calculation to be performed (debug mode):
  17.   if debug:
  18.     var outStr: seq[string]
  19.     for i in 0..<terms:
  20.       outStr.add "$1**$2" % [$x[i], $pow]
  21.     echo "(" & outStr.join(" + ") & ")"
  22.   # Raise to exponent:
  23.   var powX: array[terms, mpz_t]
  24.   for i in 0..<terms:
  25.     mpz_pow_ui powX[i], x[i], pow.culong
  26.   if debug:
  27.     echo "==\n(" & powX.join(" + ") & ")"
  28.   # Calculate sum:
  29.   var sum: mpz_t
  30.   mpz_init sum
  31.   for i in 0..<terms:
  32.     mpz_add sum, sum, powX[i]
  33.   if debug:
  34.     echo "==\n$1\n" % $sum
  35.   return sum
  36.  
  37. proc searchForTarget(loopsMax = int.high, targetMax = 2_000_000_000) =
  38.   ## Tries random number combinations until their sum is <targetMax.
  39.   randomize 19811019
  40.   var mpzTargetMax: mpz_t
  41.   mpz_init mpzTargetMax
  42.   mpz_set_si mpzTargetMax, targetMax
  43.   var loopCount = 0
  44.   while loopCount < loopsMax:
  45.     inc loopCount
  46.     if loopCount %% 1_000_000 == 0:
  47.       echo "Tried $1 combinations..." % $loopCount
  48.     let x = getRandomMpzArr()
  49.     let sum = getExpSum(x)
  50.     let cmp = mpz_cmpabs(sum, mpzTargetMax)
  51.     if cmp < 0:
  52.       echo "SUCCESS!!!"
  53.       discard getExpSum(x, true)
  54.       quit 1
  55.  
  56. when isMainModule:
  57.   searchForTarget()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement