home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume27 / calc-2.9.0 / part17 < prev    next >
Encoding:
Text File  |  1993-12-07  |  59.2 KB  |  2,027 lines

  1. Newsgroups: comp.sources.unix
  2. From: dbell@canb.auug.org.au (David I. Bell)
  3. Subject: v27i144: calc-2.9.0 - arbitrary precision C-like programmable calculator, Part17/19
  4. References: <1.755316719.21314@gw.home.vix.com>
  5. Sender: unix-sources-moderator@gw.home.vix.com
  6. Approved: vixie@gw.home.vix.com
  7.  
  8. Submitted-By: dbell@canb.auug.org.au (David I. Bell)
  9. Posting-Number: Volume 27, Issue 144
  10. Archive-Name: calc-2.9.0/part17
  11.  
  12. #!/bin/sh
  13. # this is part 17 of a multipart archive
  14. # do not concatenate these parts, unpack them in order with /bin/sh
  15. # file calc2.9.0/lib/cryrand.cal continued
  16. #
  17. CurArch=17
  18. if test ! -r s2_seq_.tmp
  19. then echo "Please unpack part 1 first!"
  20.      exit 1; fi
  21. ( read Scheck
  22.   if test "$Scheck" != $CurArch
  23.   then echo "Please unpack part $Scheck next!"
  24.        exit 1;
  25.   else exit 0; fi
  26. ) < s2_seq_.tmp || exit 1
  27. echo "x - Continuing file calc2.9.0/lib/cryrand.cal"
  28. sed 's/^X//' << 'SHAR_EOF' >> calc2.9.0/lib/cryrand.cal
  29. X * values are kept.
  30. X *
  31. X * Unlike the first and second forms of this function, the shuffle
  32. X * generator function is not seeded before or after the call.  The 
  33. X * current state is used to generate a new quadratic residue of n=p*q.
  34. X *
  35. X *
  36. X * Third form of call:  scryrand(seed,len1,len2)
  37. X *
  38. X * In the third form, 'len1' and 'len2' guide this function in selecting
  39. X * internally used prime numbers.  The larger the lengths, the longer
  40. X * the time this function will take.  The impact on execution time of
  41. X * cryrand() and random() may also be noticed, but not as much.
  42. X *
  43. X * If a length is '-1', then the default lengths (248 for len1, and 264
  44. X * for len2) are used.  The call scryrand(0,-1,-1) recreates the initial
  45. X * crypto state the slow and hard way.  (use scryrand(0) or srandom(0))
  46. X *
  47. X * This function can take a long time to call given reasonable values
  48. X * of len1 and len2.  On a Pyramid R3000, the time to seed was:
  49. X *
  50. X *    Approx value    digits   seed time
  51. X *      of len1+len2   in n=p*q       in sec
  52. X *    ------------   --------       ------
  53. X *          8           3         0.53
  54. X *         16           5         0.54
  55. X *         32          10         0.79
  56. X *         64          20         1.17
  57. X *        128          39         2.89
  58. X *        200          61         4.68
  59. X *        256          78         7.49
  60. X *        322         100        12.47
  61. X *        464         140        35.56
  62. X *        512         155        53.57
  63. X *        664         200        83.97
  64. X *        830         250       122.93
  65. X *        996         300       242.49
  66. X *       1024         309       295.66
  67. X *       1328         400       663.44
  68. X *       1586         478      2002.10
  69. X *       1660         500      1643.45  (Faster mult/square methods kick in
  70. X *       1992         600      2885.81   in certain cases. Type  help config
  71. X *       2048         617      1578.06   in calc for more details.)
  72. X *
  73. X *     NOTE: The small lengths above are given for comparison 
  74. X *           purposes and are NOT recommended for actual use.
  75. X *
  76. X *     NOTE: Generating crypto pseudo-random numbers is MUCH 
  77. X *           faster than seeding a crypto generator.
  78. X *
  79. X *     NOTE: This calc lib file is intended for demonstration 
  80. X *           purposes.  Writing a C program (with possible assembly 
  81. X *           or libmp assist) would produce a faster generator.
  82. X *
  83. X *
  84. X * Fourth form of call:  scryrand(seed,ip,iq,ir)
  85. X *
  86. X * In the fourth form, 'ip', 'iq' and 'ir' serve as initial search
  87. X * values for the two Blum primes 'p' and 'q' and an associated
  88. X * quadratic residue 'r' respectively.  Unlike the 3rd form, where 
  89. X * lengths are given, the fourth form allows one to specify minimum 
  90. X * search values.
  91. X *
  92. X * The 'seed' value is interpreted as follows:
  93. X *
  94. X *   If seed > 0:
  95. X *
  96. X *    Seed and use the shuffle generator to generate 3 jump values 
  97. X *    that are in the range '[0,ip)', '[0,iq)' and '[0,ir)' respectively.
  98. X *    Start searching for legal 'p', 'q' and 'r' values by adding 
  99. X *    the jump values to their respective argument values.
  100. X *
  101. X *   If seed == 0:
  102. X *
  103. X *    Start searching for legal 'p', 'q' and 'r' values from
  104. X *    'ip', 'iq' and 'ir' respectively.
  105. X *
  106. X *    This form does not change/seed the other generators.
  107. X *
  108. X *   If seed == -1:
  109. X *
  110. X *    Let 'p' == 'ip', 'q' == 'iq' and 'r' == 'ir'.  Do not check 
  111. X *    if the value given are legal Blum primes or an associated 
  112. X *    quadratic residue respectively.
  113. X *
  114. X *    This form does not change/seed the other generators.
  115. X *
  116. X *    WARNING: No checks are performed on the args passed.
  117. X *         Passing improper values will likely produce
  118. X *         poor results, or worse!
  119. X *
  120. X *
  121. X * It should be noted that calling scryrand() while using the default
  122. X * primes took only 0.04 seconds.  Calling scryrand(0,-1,-1) took
  123. X * 47.19 seconds.
  124. X *
  125. X * The paranoid, when giving explicit lengths, should keep in mind that
  126. X * len1 and len2 are the largest powers of 2 that are less than the two 
  127. X * probable primes ('p' and 'q').  These two primes  will be used 
  128. X * internally to cryrand().  For simplicity, we refer to len1 and len2
  129. X * as bit lengths, even though they are actually 1 less then the
  130. X * minimum possible prime length.
  131. X *
  132. X * The actual lengths may exceed the lengths by slightly more than 3%.
  133. X * Furthermore, part of the strength of this generator rests on the
  134. X * difficultly to factor 'p*q'.  Thus one should select 'len1' and 'len2'
  135. X * (from which 'p' and 'q' are selected) such that factoring a 'len1+len2'
  136. X * bit number is difficult.
  137. X *
  138. X * Not being able to factor 'n=p*q' into 'p' and 'q' does not directly
  139. X * improve the crypto generator.  On the other hand, it can't hurt.
  140. X *
  141. X * There is no limit on the size of a seed.  On the other hand,
  142. X * extremely large seeds require large tables and long seed times.
  143. X * Using a seed in the range of [2^64, 2^64 * 128!) should be
  144. X * sufficient for most purposes.  An easy way to stay within this
  145. X * range to to use seeds that are between 21 and 215 digits long, or
  146. X * 64 to 780 bits long.
  147. X *
  148. X * NOTE: This function will clear any internally buffer bits.  See
  149. X *     cryrand() for details.
  150. X *
  151. X * NOTE: This function seeds the Blum cryptographically strong
  152. X *     pseudo-random number generator.
  153. X */
  154. Xdefine
  155. Xscryrand(seed,len1,len2,arg4)
  156. X{
  157. X    local rval;        /* a temporary pseudo-random value */
  158. X    local oldseed;    /* the previous seed */
  159. X    local newres;    /* the new quad res */
  160. X    local ip;        /* initial Blum prime 'p' search value */
  161. X    local iq;        /* initial Blum prime 'q' search value */
  162. X    local ir;        /* initial quadratic residue search value */
  163. X    local rlim;        /* high quadratic res search value */
  164. X
  165. X    /*
  166. X     * firewall - avoid bogus args and very trivial lengths
  167. X     */
  168. X    /* catch the case of no args - compute a different quadratic residue */
  169. X    if (isnull(seed) && isnull(len1) && isnull(len2)) {
  170. X
  171. X    /* generate the next quadratic residue */
  172. X    do {
  173. X        newres = cryres(cryrand_p, cryrand_q);
  174. X    } while (newres == cryrand_r);
  175. X    cryrand_r = newres;
  176. X    cryrand_exp = cryrand_r;
  177. X
  178. X    /* clear the internal bits */
  179. X    cryrand_left = 0;
  180. X    cryrand_bitcnt = 0;
  181. X
  182. X    /* return the current seed early */
  183. X    return (cry_seed);
  184. X    }
  185. X    if (!isint(seed)) {
  186. X    quit "bad arg: seed arg (1st) must be an integer";
  187. X    }
  188. X    if (param(0) == 4) {
  189. X    if (seed < -1) {
  190. X        quit "bad arg: with 4 args: a seed < -1 is reserved for future use";
  191. X    }
  192. X    } else {
  193. X    if (4 && seed < 0) {
  194. X        quit "bad arg: a seed arg (1st) < 0 is reserved for future use";
  195. X    }
  196. X    }
  197. X
  198. X    /*
  199. X     * 4 arg case: select or search for 'p', 'q' and 'r' from given values
  200. X     */
  201. X    if (param(0) == 4) {
  202. X
  203. X    /* set initial values */
  204. X    ip = len1;
  205. X    iq = len2;
  206. X    ir = arg4;
  207. X
  208. X    /*
  209. X     * Unless prohibited by a seed if -1, force minimum values on
  210. X     * 'ip', 'iq' and 'ir'.
  211. X     */
  212. X    if (seed >= 0) {
  213. X        if (!isint(ip) || ip < 3) {
  214. X           /* smallest Blum prime */
  215. X           ip = 3;
  216. X        }
  217. X        if (!isint(iq) || iq < 3) {
  218. X           /* smallest Blum prime */
  219. X           iq = 3;
  220. X        }
  221. X        if (!isint(ir) || ir < 4) {
  222. X           /* cryres() never selects a value < 4 */
  223. X           ir = 4;
  224. X        }
  225. X    }
  226. X
  227. X    /*
  228. X     * Determine our prime search points
  229. X     */
  230. X    if (seed > 0) {
  231. X        /* add in a random value */
  232. X        oldseed = srand(seed);
  233. X        ip += rand(ip);
  234. X        iq += rand(iq);
  235. X    }
  236. X
  237. X    /*
  238. X     * force ip <= iq
  239. X     */
  240. X    if (ip > iq) {
  241. X        swap(ip, iq);
  242. X    }
  243. X
  244. X    /*
  245. X     * find the first Blum prime 'p'
  246. X     */
  247. X    if (seed >= 0) {
  248. X        cryrand_p = nxtprime(ip,3,4);
  249. X    } else {
  250. X        /* seed == -1: assume 'ip' is a Blum prime */
  251. X        cryrand_p = ip;
  252. X    }
  253. X
  254. X    /*
  255. X     * find the 2nd Blum prime 'q' > 'p', if needed
  256. X     */
  257. X    if (seed >= 0) {
  258. X        if (iq <= cryrand_p) {
  259. X        iq = cryrand_p + 2;
  260. X        }
  261. X        cryrand_q = nxtprime(iq,3,4);
  262. X    } else {
  263. X        /* seed == -1: assume 'iq' is a Blum prime */
  264. X        cryrand_q = iq;
  265. X    }
  266. X
  267. X    /* remember our p*q Blum prime product as well */
  268. X    cryrand_n = cryrand_p*cryrand_q;
  269. X
  270. X    /*
  271. X     * search for a quadratic residue
  272. X     */
  273. X    if (seed >= 0) {
  274. X
  275. X        /* add in a random value to 'ir' if seeded */
  276. X        if (seed > 0) {
  277. X        ir += rand(ir);
  278. X        }
  279. X
  280. X        /* 
  281. X         * increment until we find a quadratic value
  282. X         *
  283. X         * p is prime and J(r,p) == 1  ==>  r is a quadratic residue of p
  284. X         * q is prime and J(q,p) == 1  ==>  r is a quadratic residue of q
  285. X         *
  286. X         * J(r,p)*J(r,q) == J(r,p*q)
  287. X         * J(r,p) and J(q,p) == 1       ==>  J(r,p*q) == 1
  288. X         * J(r,p*q) == 1           ==>  r is a quadratic residue of p*q
  289. X         *
  290. X         * Try to avoid trivial quadratic residues by forcing the search
  291. X         * over the interval [4, n-3).
  292. X         */
  293. X        rlim = cryrand_n-3;
  294. X        /* if ir is too big, drop down to the bottom of the range */
  295. X        if (ir >= rlim) {
  296. X        ir = 4;
  297. X        }
  298. X        while (jacobi(ir,cryrand_p) != 1 || jacobi(ir,cryrand_q) != 1) {
  299. X        /* if ir is too big, drop down to the bottom of the range */
  300. X        if (++ir >= rlim) {
  301. X            ir = 4;
  302. X        }
  303. X        }
  304. X    }
  305. X    cryrand_r = ir;
  306. X
  307. X    /* 
  308. X     * clear the previously unused cryrand bits & other misc setup
  309. X     */
  310. X    cryrand_left = 0;
  311. X    cryrand_bitcnt = 0;
  312. X    cryrand_exp = cryrand_r;
  313. X
  314. X    /* 
  315. X     * reseed the generator, if needed
  316. X     *
  317. X     * The crypto generator no longer needs the additive 55 and shuffle
  318. X     * generators.  We however, restore the additive 55 and shuffle
  319. X     * generators back to its seeded state in order to be sure that it
  320. X     * will be left in the same state.
  321. X     *
  322. X     * This will make more reproducible, calls to the additive 55 and
  323. X     * shuffle generator; or more reproducible, calls to this function
  324. X     * without args.
  325. X     */
  326. X    if (seed > 0) {
  327. X        ir = srand(seed);   /* ignore this return value */
  328. X        return(oldseed);
  329. X    } else {
  330. X        /* no seed change, return the current seed */
  331. X        return (cry_seed);
  332. X    }
  333. X    }
  334. X
  335. X    /*
  336. X     * If not the 4 arg case:
  337. X     *
  338. X     * convert explicit -1 args into default values
  339. X     * convert missing args into -1 values (use precomputed tables)
  340. X     */
  341. X    if ((isint(len1) && len1 != -1 && len1 < 4) ||
  342. X    (isint(len2) && len2 != -1 && len2 < 4) ||
  343. X    (!isint(len1) && isint(len2)) ||
  344. X    (isint(len1) && !isint(len2))) {
  345. X    quit "bad args: 2 & 3: if 2nd is given, must be -1 or ints > 3";
  346. X    }
  347. X    if (isint(len1) && len1 == -1) {
  348. X    len1 = 248;    /* default len1 value */
  349. X    }
  350. X    if (isint(len2) && len2 == -1) {
  351. X    len2 = 264;    /* default len2 value */
  352. X    }
  353. X    if (!isint(len1) && !isint(len2)) {
  354. X    /* from here down, -1 means use precomputed values */
  355. X    len1 = -1;
  356. X    len2 = -1;
  357. X    }
  358. X
  359. X    /*
  360. X     * force len1 <= len2
  361. X     */
  362. X    if (len1 > len2) {
  363. X    swap(len1, len2);
  364. X    }
  365. X
  366. X    /*
  367. X     * seed the generator
  368. X     */
  369. X    oldseed = srand(seed);
  370. X
  371. X    /*
  372. X     * generate p and q Blum primes
  373. X     *
  374. X     * The Blum process requires the primes to be of the form 3 mod 4.
  375. X     * We also generate n=p*q for future reference.
  376. X     *
  377. X     * We make sure that the lengths are the minimum lengths possible.
  378. X     * We want some range to select a random prime from, so we
  379. X     * go at least 3 bits higher, and as much as 3% plus 3 bits
  380. X     * higher.  Since the section is a random, how high really
  381. X     * does not matter that much, but we want to avoid going to
  382. X     * an extreme to keep the execution time from getting too long.
  383. X     *
  384. X     * Finally, we generate a quadratic residue of n=p*q.
  385. X     */
  386. X    if (len1 > 0) {
  387. X    /* generate a pseudo-random prime ~len1 bits long */
  388. X    rval = rand(2^(len1-1), 2^((int(len1*1.03))+3));
  389. X    cryrand_p = nxtprime(rval,3,4);
  390. X    } else {
  391. X    /* use precomputed 'p' value */
  392. X    cryrand_p = cryrand_init_p;
  393. X    }
  394. X    if (len2 > 0) {
  395. X    /* generate a pseudo-random prime ~len1 bits long */
  396. X    rval = rand(2^(len2-1), 2^((int(len2*1.03))+3));
  397. X    cryrand_q = nxtprime(rval,3,4);
  398. X    } else {
  399. X    /* use precomputed 'q' value */
  400. X    cryrand_q = cryrand_init_q;
  401. X    }
  402. X
  403. X    /*
  404. X     * find the quadratic residue
  405. X     */
  406. X    cryrand_n = cryrand_p*cryrand_q;
  407. X    cryrand_r = cryres(cryrand_p, cryrand_q);
  408. X
  409. X    /* 
  410. X     * clear the previously unused cryrand bits & other misc setup
  411. X     */
  412. X    cryrand_left = 0;
  413. X    cryrand_bitcnt = 0;
  414. X    cryrand_exp = cryrand_r;
  415. X
  416. X    /*
  417. X     * reseed the generator
  418. X     *
  419. X     * The crypto generator no longer needs the additive 55 and shuffle
  420. X     * generators.  We however, restore the additive 55 and shuffle
  421. X     * generators back to its seeded state in order to be sure that it
  422. X     * will be left in the same state.
  423. X     *
  424. X     * This will make more reproducible, calls to the additive 55 and
  425. X     * shuffle generator; or more reproducible, calls to this function
  426. X     * without args.
  427. X     */
  428. X    /* we do not care about this old seed */
  429. X    rval = srand(seed);
  430. X
  431. X    /*
  432. X     * return the old seed
  433. X     */
  434. X    return(oldseed);
  435. X}
  436. X
  437. X
  438. X/*
  439. X * random - a cryptographically strong pseudo-random number generator
  440. X *
  441. X * usage:
  442. X *    random()     - generate a pseudo-random integer >=0 and < 2^64
  443. X *    random(a)     - generate a pseudo-random integer >=0 and < a
  444. X *    random(a,b)    - generate a pseudo-random integer >=a and <= b
  445. X *
  446. X * returns:
  447. X *    a large cryptographically strong pseudo-random number  (see usage)
  448. X *
  449. X * This function is just another interface to the crypto generator.
  450. X * (see the cryrand() function).
  451. X *
  452. X * When no arguments are given, a pseudo-random number in the half open
  453. X * interval [0,2^64) is produced.  This form is identical to calling
  454. X * cryrand(64).
  455. X *
  456. X * When 1 argument is given, a pseudo-random number in the half open interval
  457. X * [0,a) is produced.
  458. X *
  459. X * When 2 arguments are given, a pseudo-random number in the closed interval
  460. X * [a,b] is produced.
  461. X *
  462. X * This generator uses the crypto to return a large pseudo-random number.
  463. X *
  464. X * The input values a and b, if given, must be integers.
  465. X *
  466. X * Internally, bits are produced log2(log2(n=p*q)) at a time.  If a
  467. X * call to this function does not exhaust all of the collected bits,
  468. X * the unused bits will be saved away and used at a later call.
  469. X * Setting the seed via scryrand(), srandom() or cryrand(len,1)
  470. X * will clear out all unused bits.
  471. X *
  472. X * NOTE: The BSD random() function returns only 31 bits, while we return 64.
  473. X *
  474. X * NOTE: This function is the Blum cryptographically strong
  475. X *     pseudo-random number generator!
  476. X */
  477. Xdefine
  478. Xrandom(a,b)
  479. X{
  480. X    local range;        /* we must generate [0,range) first */
  481. X    local offset;        /* what to add to get a adjusted range */
  482. X    local rangebits;        /* the number of bits in range */
  483. X    local ret;            /* pseudo-random bit value */
  484. X
  485. X    /*
  486. X     * setup and special cases
  487. X     */
  488. X    /* deal with the rand() case */
  489. X    if (isnull(a) && isnull(b)) {
  490. X    /* no args means return 64 bits */
  491. X    return(cryrand(64));
  492. X    }
  493. X    /* firewall - args, if given must be in integers */
  494. X    if (!isint(a) || (!isnull(b) && !isint(b))) {
  495. X    quit "bad args: args, if given, must be integers";
  496. X    }
  497. X    /* convert rand(x) into rand(0,x-1) */
  498. X    if (isnull(b)) {
  499. X    /* convert call into a closed interval */
  500. X    b = a-1;
  501. X    a = 0;
  502. X    /* firewall - rand(0) should act like rand(0,0) */
  503. X    if (b == -1) {
  504. X        return(0);
  505. X    }
  506. X    }
  507. X    /* determine the range and offset */
  508. X    if (a >= b) {
  509. X    /* deal with the case of rand(a,a) */
  510. X    if (a == b) {
  511. X        /* not very random, but it is true! */
  512. X        return(a);
  513. X    }
  514. X    range = a-b+1;
  515. X    offset = b;
  516. X    } else {
  517. X    /* convert random(a,b), where a<b, into random(b,a) */
  518. X    range = b-a+1;
  519. X    offset = a;
  520. X    }
  521. X    rangebits = highbit(range-1)+1;
  522. X    /*
  523. X     * At this point, we seek a pseudo-random number [0,range) to which
  524. X     * we will add offset to produce a number [offset,range+offset).
  525. X     */
  526. X
  527. X    /*
  528. X     * loop until we get a value that is in range
  529. X     *
  530. X     * We will obtain pseudo-random values over the range [0,2^rangebits)
  531. X     * where 2^rangebits >= range and 2^(rangebits-1) < range.  We
  532. X     * will ignore any results that are > the range that we want.
  533. X     *
  534. X     * A note in modulus biasing:
  535. X     *
  536. X     * We will not fall into the trap of thinking that we can simply take
  537. X     * a value mod 'range'.  Consider the case where 'range' is '80'
  538. X     * and we are given pseudo-random numbers [0,100).  If we took them
  539. X     * mod 80, then the numbers [0,20) would be produced more often
  540. X     * because the numbers [81,100) mod 80 wrap back into [0,20).
  541. X     */
  542. X    do {
  543. X    /* obtain a pseudo-random value */
  544. X    ret = cryrand(rangebits);
  545. X    } while (ret >= range);
  546. X
  547. X    /*
  548. X     * return the adjusted range value
  549. X     */
  550. X    return(ret+offset);
  551. X}
  552. X
  553. X
  554. X/*
  555. X * srandom - seed the cryptographically strong pseudo-random number generator
  556. X *
  557. X * given:
  558. X *    seed    a random number seed
  559. X *
  560. X * returns:
  561. X *      the previous seed
  562. X *
  563. X * This function is just another interface to the crypto generator.
  564. X * (see the scryrand() function).
  565. X *
  566. X * This function makes indirect use of the additive 55 and shuffle 
  567. X * generator.
  568. X *
  569. X * There is no limit on the size of a seed.  On the other hand,
  570. X * extremely large seeds require large tables and long seed times.
  571. X * Using a seed in the range of [2^64, 2^64 * 128!) should be
  572. X * sufficient for most purposes.  An easy way to stay within this
  573. X * range to to use seeds that are between 21 and 215 digits long, or
  574. X * 64 to 780 bits long.
  575. X *
  576. X * NOTE: Calling this function will clear any internally buffer bits.
  577. X *     See cryrand() for details.
  578. X *
  579. X * NOTE: This function seeds the Blum cryptographically strong
  580. X *     pseudo-random number generator!
  581. X */
  582. Xdefine
  583. Xsrandom(seed)
  584. X{
  585. X    if (!isint(seed)) {
  586. X    quit "bad arg: seed must be an integer";
  587. X    }
  588. X    if (seed < 0) {
  589. X    quit "bad arg: seed < 0 is reserved for future use";
  590. X    }
  591. X    return(scryrand(seed));
  592. X}
  593. X
  594. X
  595. X/*
  596. X * randstate - set/get the state of all of the generators
  597. X *
  598. X * usage:
  599. X *    randstate()    return the current state
  600. X *    randstate(0)    return the previous state, set the default state
  601. X *    randstate(cobj)    return the previous state, set a new state
  602. X *
  603. X * In the first form: randstate()
  604. X *
  605. X *    This function returns an cryobj object containing information
  606. X *    about the current state of all of the generators.
  607. X *
  608. X * In the second form: randstate(0)
  609. X *
  610. X *    This function sets all of the generators to the default initial
  611. X *    state (i.e., the state when this library was loaded).
  612. X *
  613. X *    This function returns an cryobj object containing information
  614. X *    about the previous state of all of the generators.
  615. X *
  616. X * In the third form: randstate(cobj)
  617. X *
  618. X *    This function sets all of the generators to the state as found
  619. X *    in the cryobj object.
  620. X *
  621. X *    This function returns an cryobj object containing information
  622. X *    about the previous state of all of the generators.
  623. X *
  624. X * This function may be used to save and restore cryrand() & random()
  625. X * generator states.  For example:
  626. X *
  627. X *    state = randstate()        <-- save the current state
  628. X *    random()            <-- print the next 64 bits
  629. X *    randstate(state)        <-- restore previous state
  630. X *    random()            <-- print the same 64 bits
  631. X *
  632. X * One may quickly reseed a generator.  For example:
  633. X *
  634. X *    srandom(1,330,350)        <-- seed the generator
  635. X *    seed1state = randstate()    <-- remember this 1st seeded state
  636. X *    random()            <-- print 1st 64 bits seed 1 generator
  637. X *    srandom(2,331,351)        <-- seed the generator again
  638. X *    seed2state = randstate()    <-- remember this 2nd seeded state
  639. X *    random()            <-- print 1st 64 bits seed 2 generator
  640. X *
  641. X *    randstate(seed1state)        <-- reseed to the 1st seeded state
  642. X *    random()            <-- reprint 1st 64 bits seed 1 generator
  643. X *    randstate(seed2state)        <-- reseed to the 2nd seeded state
  644. X *    random()            <-- reprint 1st 64 bits seed 2 generator
  645. X *
  646. X *    oldstate = randstate(0)        <-- seed to the default generator
  647. X *    random()            <-- print 1st 64 bits from default
  648. X *    a55rand()            <-- print 1st 64 bits a55 generator
  649. X *    prevstate = randstate(oldstate)    <-- restore seed 2 generator
  650. X *    random()            <-- print 2nd 64 bits seed 2 generator
  651. X *    randstate(prevstate)        <-- restore def generator in progress
  652. X *    random()            <-- print 2nd 64 bits default generator
  653. X *    a55rand()            <-- print 2nd 64 bits a55 generator
  654. X *
  655. X * given:
  656. X *    cobj    if a cryobj object, use that object to set the current state
  657. X *        if 0, set to the default state
  658. X *
  659. X * return:
  660. X *    return the state of the crypto pseudo-random number generator in
  661. X *           the form of an cryobj object, as it was prior to this call
  662. X *
  663. X * NOTE: No checking is performed on the data the 3rd form (cryobj object
  664. X *     arg) is used.  The user must ensure that the arg represents a valid
  665. X *     generator state.
  666. X *
  667. X * NOTE: When using the second form (passing an integer arg), only 0 is
  668. X *     defined.  All other integer values are reserved for future use.
  669. X */
  670. Xdefine
  671. Xrandstate(arg)
  672. X{
  673. X    /* declare our objects */
  674. X    local obj cryobj x;        /* firewall comparator */
  675. X    local obj cryobj prev;    /* previous states of the generators */
  676. X    local junk;            /* dummy holder of random values */
  677. X
  678. X    /* firewall */
  679. X    if (!isint(arg) && !istype(arg,x) && !isnull(arg)) {
  680. X    quit "bad arg: argument must be integer, an cryobj object or missing";
  681. X    }
  682. X    if (isint(arg) && arg != 0) {
  683. X        quit "bad arg:  non-zero integer arguments are reserved for future use";
  684. X    }
  685. X
  686. X    /*
  687. X     * save the current state
  688. X     */
  689. X    prev.p = cryrand_p;
  690. X    prev.q = cryrand_q;
  691. X    prev.r = cryrand_r;
  692. X    prev.exp = cryrand_exp;
  693. X    prev.left = cryrand_left;
  694. X    prev.bitcnt = cryrand_bitcnt;
  695. X    prev.a55j = add55_j;
  696. X    prev.a55k = add55_k;
  697. X    prev.seed = cry_seed;
  698. X    prev.shufy = shuf_y;
  699. X    prev.shufsz = shuf_size;
  700. X    prev.shuftbl = shuf_tbl;
  701. X    prev.a55tbl = add55_tbl;
  702. X    if (isnull(x)) {
  703. X    /* if no args, just return current state */
  704. X    return (prev);
  705. X    }
  706. X
  707. X    /*
  708. X     * deal with the cryobj arg - set the state
  709. X     */
  710. X    if (istype(arg, x)) {
  711. X    /* set the state from this object */
  712. X    cryrand_p = arg.p;
  713. X    cryrand_q = arg.q;
  714. X    cryrand_n = cryrand_p*cryrand_q;
  715. X    cryrand_r = arg.r;
  716. X    cryrand_exp = arg.exp;
  717. X    cryrand_left = arg.left;
  718. X    cryrand_bitcnt = arg.bitcnt;
  719. X    add55_j = arg.a55j;
  720. X    add55_k = arg.a55k;
  721. X    cry_seed = arg.seed;
  722. X    add55_seed64 = randreseed64(cry_seed);
  723. X    shuf_y = arg.shufy;
  724. X    shuf_size = arg.shufsz;
  725. X    shuf_shift = (64-highbit(shuf_size));
  726. X    mat shuf_tbl[shuf_size];
  727. X    shuf_tbl = arg.shuftbl;
  728. X    add55_tbl = arg.a55tbl;
  729. X
  730. X    /*
  731. X     * deal with the 0 integer arg - set the default initial state
  732. X     */
  733. X    } else if (isint(arg) && arg == 0) {
  734. X    cryrand_p = cryrand_init_p;
  735. X    cryrand_q = cryrand_init_q;
  736. X    cryrand_n = cryrand_p * cryrand_q;
  737. X    cryrand_r = cryrand_init_r;
  738. X    cryrand_exp = cryrand_r;
  739. X    cryrand_left = 0;
  740. X    cryrand_bitcnt = 0;
  741. X    cry_seed = 0;
  742. X    cry_seed = sshufrand(0);
  743. X    }
  744. X
  745. X    /*
  746. X     * return the previous state
  747. X     */
  748. X    return (prev);
  749. X}
  750. X
  751. X
  752. X/*
  753. X * nxtprime - find a probable prime >= n_arg
  754. X *
  755. X * usage:
  756. X *    nxtprime(n_arg)
  757. X *    nxtprime(n_arg, modval, modulus)
  758. X *
  759. X * given:
  760. X *    n_arg            lower bound of the search
  761. X *    [modval modulus]    if given, look for numbers mod modulus == modval
  762. X *
  763. X * returns:
  764. X *    A number is that is very likely prime.
  765. X *
  766. X * In the first case 'nxtprime(n_arg)', this function returns a probable
  767. X * prime >= n_arg.  In the second case 'nxtprime(n_arg, v, u)', this
  768. X * function returns a probable prime >= n_arg that is also == v mod u.
  769. X *
  770. X * This function will not skip over a prime, through there is a
  771. X * extremely unlikely chance that it will return a composite.
  772. X * The odds that a number returned by this function is not prime
  773. X * are 1 in 4^50.  The failure rate of this function is many orders
  774. X * or magnitude lower than the failure rate due to a hardware error.
  775. X *
  776. X * NOTE: This function can take a long time, given a large value of n_arg.
  777. X */
  778. Xdefine
  779. Xnxtprime(n_arg, modval, modulus)
  780. X{
  781. X    local modgcd;        /* gcd(modulus,modval) */
  782. X    local n;            /* value >= n_arg that is being tested */
  783. X    local j;
  784. X
  785. X    /*
  786. X     * firewall
  787. X     */
  788. X    if (!isint(n_arg)) {
  789. X    quit "bad args: 1st arg must be an integer";
  790. X    }
  791. X    if (!isnull(modulus) && !isint(modval)) {
  792. X    quit "bad args: 3rd arg, if 2nd arg is given, must be an integer";
  793. X    }
  794. X    if (!isnull(modulus) && (!isint(modulus) || modulus <= 0)) {
  795. X    quit "bad args: 3nd arg, if given, must be an integer > 0";
  796. X    }
  797. X
  798. X    /*
  799. X     * get values < 3 out of the way
  800. X     */
  801. X    n = n_arg;
  802. X    if (n < 3) {
  803. X    /* get the even prime out of the way, if possible */
  804. X    if (isnull(modulus) ||
  805. X        modulus == 1 ||
  806. X        (n%modulus == modval%modulus)) {
  807. X        /*
  808. X         * 2 is the greatest odd prime, because
  809. X         * 2 is the least even prime  :-)
  810. X         */
  811. X        return(2);
  812. X    }
  813. X    /* we have eliminated everything < 3 */
  814. X    n = 3;
  815. X    }
  816. X
  817. X    /*
  818. X     * convert nxtprime(n) to nxtprime(n,1,2)
  819. X     * convert nxtprime(n,x,1) to nxtprime(n,1,2)
  820. X     * convert nxtprime(n,a,b) to nxtprime(n,a mod b,b)
  821. X     */
  822. X    if (isnull(modulus) || modulus < 2) {
  823. X    modulus = 2;
  824. X    modval = 1;
  825. X    }
  826. X    modval %= modulus;
  827. X
  828. X    /*
  829. X     * catch cases where no more primes == 'modval' mod 'modulus' exist
  830. X     */
  831. X    modgcd = gcd(modval,modulus);
  832. X    if (modgcd > 1) {
  833. X
  834. X    /* if beyond the modgcd, then no primes can exist */
  835. X        if (n > modgcd) {
  836. X        print "n_arg:",n_arg,"  modval:",modval,"  modulus:",modulus;
  837. X        quit "no such prime of that form exists";
  838. X    }
  839. X
  840. X    /* else n <= modgcd, then our only chance is if modgcd is prime */
  841. X    /* reject if modgcd has an obvious prime factor */
  842. X    if (modgcd > 10 && gcd(modgcd,nxtprime_pfact10) != 1) {
  843. X        print "n_arg:",n_arg,"  modval:",modval,"  modulus:",modulus;
  844. X        quit "no such prime of that form exists";
  845. X    }
  846. X    if (modgcd > 100 && gcd(modgcd,nxtprime_pfact100) != 1) {
  847. X        print "n_arg:",n_arg,"  modval:",modval,"  modulus:",modulus;
  848. X        quit "no such prime of that form exists";
  849. X    }
  850. X    if (modgcd > 1000 && gcd(modgcd,nxtprime_pfact1000) != 1) {
  851. X        print "n_arg:",n_arg,"  modval:",modval,"  modulus:",modulus;
  852. X        quit "no such prime of that form exists";
  853. X    }
  854. X
  855. X    /* do 50 probable prime tests, for a 1 in 4^50 false prime rate */
  856. X    if (!ptest(modgcd,50)) {
  857. X        print "n_arg:",n_arg,"  modval:",modval,"  modulus:",modulus;
  858. X        quit "no such prime of that form exists";
  859. X    }
  860. X
  861. X    /* modgcd is the only prime >= n */
  862. X    return(modgcd);
  863. X    }
  864. X
  865. X    /*
  866. X     * bump n up to the next possible case
  867. X     *
  868. X     * n will be an odd number == 'modval' mod 'modulus'
  869. X     */
  870. X    if (n%modulus != modval) {
  871. X    j = n - (n%modulus) + modval;
  872. X    if (j < n) {
  873. X        n = j+modulus;
  874. X    } else {
  875. X        n = j;
  876. X    }
  877. X    }
  878. X    if (n%2 == 0) {
  879. X    n += modulus;
  880. X    }
  881. X
  882. X    /* look for a prime */
  883. X    n = n-modulus;
  884. X    do {
  885. X    /* try the next integer */
  886. X    n = n+modulus;
  887. X
  888. X    /* reject if it has an obvious prime factor */
  889. X    if (n > 10 && gcd(n,nxtprime_pfact10) != 1) {
  890. X        continue;
  891. X    }
  892. X    if (n > 100 && gcd(n,nxtprime_pfact100) != 1) {
  893. X        continue;
  894. X    }
  895. X    if (n > 1000 && gcd(n,nxtprime_pfact1000) != 1) {
  896. X        continue;
  897. X    }
  898. X
  899. X    /* do 50 probable prime tests */
  900. X    if (!ptest(n,50)) {
  901. X        continue;
  902. X    }
  903. X
  904. X    /* n is very likely a prime number */
  905. X    return(n);
  906. X
  907. X    } while (1);
  908. X}
  909. X
  910. X
  911. X/*
  912. X * cryobj - how to initialize a cryobj object
  913. X *
  914. X * given:
  915. X *    p        first Blum prime (prime 3 mod 4)
  916. X *    q        second Blum prime (prime 3 mod 4)
  917. X *    r        quadratic residue of n=p*q
  918. X *    exp        used in computing crypto good bits
  919. X *    left        bits unused from the last cryrand() call
  920. X *    bitcnt        left contains bitcnt crypto good bits
  921. X *    a55j        1st additive 55 table pointer
  922. X *    a55k        2nd additive 55 table pointer
  923. X *    seed        last seed set by sa55rand() or 0
  924. X *    shufy        Y (previous a55rand() output for shuffle)
  925. X *    shufsz        size of the shuffle table
  926. X *    shuftbl        a matrix of shufsz entries
  927. X *    a55tbl        additive 55 generator state table
  928. X *
  929. X * return:
  930. X *    an cryobj object
  931. X *
  932. X * NOTE: This function, by convention, returns an cryobj object.
  933. X */
  934. Xdefine
  935. Xcryobj(p,q,r,exp,left,bitcnt,a55j,a55k,seed,shufy,shufsz,shuftbl,a55tbl)
  936. X{
  937. X    /* declare our objects */
  938. X    local obj cryobj x;
  939. X
  940. X    /* firewall */
  941. X    if (!isint(p) || !isint(q) || !isint(r) || !isint(exp) || \
  942. X    !isint(left) || !isint(bitcnt) || !isint(a55j) || \
  943. X    !isint(a55k) || !isint(seed) || !isint(shufy) || !isint(shufsz)) {
  944. X    quit "bad args: first 11 args must be integers";
  945. X    }
  946. X    if (!ismat(shuftbl) || matdim(shuftbl) != 1 || \
  947. X    matmin(shuftbl,1) != 0 || matmax(shuftbl,1) != shuf_size-1) {
  948. X    quit "bad arg: 12th is not a mat[0:shuf_size-1]";
  949. X    }
  950. X    if (!ismat(a55tbl) || matdim(a55tbl) != 1 || \
  951. X    matmin(a55tbl,1) != 0 || matmax(a55tbl,1) != 54) {
  952. X    quit "bad arg: 13th is not a mat[0:54]";
  953. X    }
  954. X
  955. X    /* initialize object with default startup values */
  956. X    x.p = p;
  957. X    x.q = q;
  958. X    x.r = r;
  959. X    x.exp = exp;
  960. X    x.left = left;
  961. X    x.bitcnt = bitcnt;
  962. X    x.a55j = a55j;
  963. X    x.a55k = a55k;
  964. X    x.seed = seed;
  965. X    x.shufy = shuf_y;
  966. X    x.shufsz = shuf_size;
  967. X    x.shuftbl = shuf_tbl;
  968. X    x.a55tbl = a55tbl;
  969. X
  970. X    /* return the initialized object */
  971. X    return (x);
  972. X}
  973. X
  974. X
  975. X/*
  976. X * cryobj_print - print the value of a cryobj object
  977. X *
  978. X * usage:
  979. X *    a    an cryobj object
  980. X *
  981. X * NOTE: This function is called automatically when an cryobj object
  982. X *       is displayed.
  983. X */
  984. Xdefine
  985. Xcryobj_print(a)
  986. X{
  987. X    /* declare our objects */
  988. X    local obj cryobj x;        /* firewall comparator */
  989. X
  990. X    /* firewall */
  991. X    if (!istype(a, x)) {
  992. X    quit "bad arg: arg is not an cryobj object";
  993. X    }
  994. X    if (!ismat(a.shuftbl) || matdim(a.shuftbl) != 1 || \
  995. X    matmin(a.shuftbl,1) != 0 || matmax(a.shuftbl,1) != a.shufsz-1) {
  996. X    quit "bad arg: 12th is not a mat[0:shuf_size-1]";
  997. X    }
  998. X    if (!ismat(a.a55tbl) || matdim(a.a55tbl) != 1 || \
  999. X    matmin(a.a55tbl,1) != 0 || matmax(a.a55tbl,1) != 54) {
  1000. X    quit "bad arg: 13th is not a mat[0:54]";
  1001. X    }
  1002. X
  1003. X    /* print the value */
  1004. X    print "cryobj(" : a.p : "," : a.q : "," : a.r : "," : a.exp : "," : \
  1005. X      a.left : "," : a.bitcnt : "," : a.a55j : "," : a.a55k : "," : \
  1006. X      a.seed : "," : a.shufy : "," : a.shufsz : \
  1007. X      ",[" : a.shuftbl[0] : "," : a.shuftbl[1] : "," : \
  1008. X      a.shuftbl[2] : ",...," : a.shuftbl[52] : "," : \
  1009. X      a.shuftbl[53] : "," : a.shuftbl[54] : "]" : \
  1010. X      ",[" : a.a55tbl[0] : "," : a.a55tbl[1] : "," : \
  1011. X      a.a55tbl[2] : ",...," : a.a55tbl[52] : "," : \
  1012. X      a.a55tbl[53] : "," : a.a55tbl[54] : "])" : ;
  1013. X}
  1014. X
  1015. X
  1016. X/*
  1017. X * cryres - find a pseudo-random quadratic residue for scryrand() and cryrand()
  1018. X *
  1019. X * given:
  1020. X *    p    first prime
  1021. X *    q    second prime
  1022. X *
  1023. X * returns:
  1024. X *    a number that is a quadratic residue of n=p*q
  1025. X *
  1026. X * This function is returns the pseudo-random quadratic residue of
  1027. X * the product of two primes.  Normally this function is called
  1028. X * only by the crypto generator.
  1029. X *
  1030. X * NOTE: No check is made to ensure that the values passed are primes.
  1031. X *
  1032. X * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  1033. X *       generate some internal values.
  1034. X */
  1035. Xdefine
  1036. Xcryres(p,q)
  1037. X{
  1038. X    local rval;        /* a temporary pseudo-random value */
  1039. X    local sqrpow;    /* a power of 2 starting > n^(3/4) */
  1040. X    local quadres;    /* 0 or a quadratic residue of n = p*q */
  1041. X    local n;        /* n=p*q */
  1042. X    local j;
  1043. X
  1044. X    /*
  1045. X     * firewall
  1046. X     */
  1047. X    if (!isint(p) || !isint(q) || p < 3 || q < 3) {
  1048. X    quit "bad args: p and q must be integers > 2";
  1049. X    }
  1050. X
  1051. X    /*
  1052. X     * find a pseudo-random quadratic residue of n = p*q
  1053. X     *
  1054. X     * To find a pseudo-random quadratic residue, we will generate
  1055. X     * pseudo-random numbers to try in the interval [2^sqrpow,n-3),
  1056. X     * where 2^sqrpow is the first power of 2 > n^(3/4).  This range
  1057. X     * helps us avoid selecting trivial residues abs(quadres mod n=p*q)
  1058. X     * is tiny.  We will never select a residue < 4.
  1059. X     *
  1060. X     * When we fail to find a quadratic residue after 1009 tries, we will
  1061. X     * drop sqrpow by 1 and start at another pseudo-random location.
  1062. X     *
  1063. X     * It is very unlikely that we will need to search more than a
  1064. X     * few numbers to find a quadratic residue of n = p*q.
  1065. X     *
  1066. X     * We will reject any quadratic residue that is a square of
  1067. X     * itself, mod n=p*q.
  1068. X     */
  1069. X    n = p*q;
  1070. X    quadres = 0;
  1071. X    sqrpow = highbit(n)//4*3;
  1072. X    do {
  1073. X    /* generate a pseudo-random starting point */
  1074. X    rval = rand(2^sqrpow, n-4);
  1075. X
  1076. X    /* look for 1009 times or until >= cryrand_n */
  1077. X    for (j=0; j < 1009; ++j, ++rval) {
  1078. X
  1079. X        /*
  1080. X         * check if we have a quadratic residue of n = p*q
  1081. X         *
  1082. X         * p is prime and J(r,p) == 1  ==>  r is a quadratic residue of p
  1083. X         * q is prime and J(q,p) == 1  ==>  r is a quadratic residue of q
  1084. X         *
  1085. X         * J(r,p)*J(r,q) == J(r,p*q)
  1086. X         * J(r,p) and J(q,p) == 1       ==>  J(r,p*q) == 1
  1087. X         * J(r,p*q) == 1           ==>  r is a quadratic residue of p*q
  1088. X         */
  1089. X        if (jacobi(rval,p) == 1 && jacobi(rval,q) == 1) {
  1090. X        quadres = rval;
  1091. X        break;
  1092. X        }
  1093. X    }
  1094. X
  1095. X    /* setup for a new pseudo-random starting point if we found nothing */
  1096. X    if (quadres == 0) {
  1097. X        /* reduce sqrpow if reasonable */
  1098. X        if (sqrpow > 2) {
  1099. X        --sqrpow;
  1100. X        }
  1101. X    }
  1102. X    } while (quadres == 0 || ((quadres^2)%n) == quadres);
  1103. X
  1104. X    /*
  1105. X     * return the quadratic residue of n = p*q
  1106. X     */
  1107. X    return (quadres);
  1108. X}
  1109. X
  1110. X
  1111. X/*
  1112. X * randreseed64 - scramble a 64 bit seed
  1113. X *
  1114. X * given:
  1115. X *    a 64 bit seed
  1116. X *
  1117. X * returns:
  1118. X *    a 64 scrambled seed, or 0 if seed was 0
  1119. X *
  1120. X * It is 'nice' when a seed of "n" produces a 'significantly different'
  1121. X * sequence than a seed of "n+1".  Generators, by convention, assign
  1122. X * special significance to the seed of '0'.  It is an unfortunate that
  1123. X * people often pick small seed values, particularly when large seed
  1124. X * are of significance to the generators found in this file.
  1125. X *
  1126. X * If 'seed' is 0, then 0 is returned.  If 'seed' is non-zero, we will
  1127. X * produce a different and unique new scrambled 'seed'.  This scrambling
  1128. X * will effectively eliminate the human factors and perceptions that
  1129. X * are noted above.
  1130. X *
  1131. X * It should be noted that the purpose of this process to scramble a seed
  1132. X * ONLY.  We do not care if these generators produce good random numbers.
  1133. X * We only want to help eliminate the human factors and perceptions
  1134. X * noted above.
  1135. X *
  1136. X * This function scrambles the low 64 bits of a seed, by mapping [0,2^64)
  1137. X * into [0,2^64).  This map is one-to-one and onto.  Mapping is performed
  1138. X * using  a linear congruence generator of the form:
  1139. X *
  1140. X *        X1 <-- (a*X0 + c) mod m
  1141. X *
  1142. X * The generator are based on the linear congruential generators found in
  1143. X * Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  1144. X * vol 2, 2nd edition (1981), Section 3.6, pages 170-171.
  1145. X *
  1146. X * Because we process 64 bits we will take:
  1147. X *
  1148. X *        m = 2^64            (based on note ii)
  1149. X *
  1150. X * We will scan the Rand book of numbers to look for an 'a' such that:
  1151. X *
  1152. X *        a mod 8 == 5            (based on note iii)
  1153. X *        0.01*m < a < 0.99*m        (based on note iv)
  1154. X *        0.01*2^64 < a < 0.99*2^64
  1155. X *
  1156. X * To help keep the generators independent, we want:
  1157. X *
  1158. X *        a is prime
  1159. X *
  1160. X * The choice of an adder 'c' is considered immaterial according (based 
  1161. X * in note v).  Knuth suggests 'c==1' or 'c==a'.  We elect to select 'c' 
  1162. X * using the same process as we used to select 'a'.  The choice is 
  1163. X * 'immaterial' after all, and as long as:
  1164. X *
  1165. X *        gcd(c, m) == 1        (based on note v)
  1166. X *        gcd(c, 2^64) == 1
  1167. X *
  1168. X * the concerns are met.   It can be shown that if we have:
  1169. X *
  1170. X *        gcd(a, c) == 1
  1171. X *
  1172. X * then the adders and multipliers will be more independent.
  1173. X *
  1174. X * We will obtain the values 'a' and 'c for our generator from the 
  1175. X * Rand book of numbers.  Because m=2^64 is 20 decimal digits long, we 
  1176. X * will search the Rand book of numbers 20 at a time.  We will skip any 
  1177. X * of the 55 values that were used to initialize the additive 55 generators. 
  1178. X * The values obtained from the Rand book are:
  1179. X *
  1180. X *        a = 6316878969928993981
  1181. X *        c = 1363042948800878693
  1182. X *
  1183. X * As we stated before, we must map 0 ==> 0.  The linear congruence
  1184. X * generator would normally map as follows:
  1185. X *
  1186. X *    0 ==> 1363042948800878693    (0 ==> c)
  1187. X *
  1188. X * To determine which value maps back into 0, we compute:
  1189. X *
  1190. X *    (-c*minv(a,m)) % m
  1191. X *
  1192. X * and thus we find that the congruence generator would also normally map:
  1193. X *
  1194. X *    10239951819489363767 ==> 0
  1195. X *
  1196. X * To overcome this, and preserve the 1-to-1 and onto map, we force:
  1197. X *
  1198. X *    0 ==> 0
  1199. X *    10239951819489363767 ==> 1363042948800878693
  1200. X *
  1201. X * To repeat, this function converts a values into a seed value.  With the
  1202. X * except of 'seed == 0', every value is mapped into a unique seed value.
  1203. X * This mapping need not be complex, random or secure.  All we attempt
  1204. X * to do here is to allow humans who pick small or successive seed values
  1205. X * to obtain reasonably different sequences from the generators below.
  1206. X *
  1207. X * NOTE: This is NOT a random number generator.  This function is intended
  1208. X *     to be used internally by sa55rand() and sshufrand().
  1209. X */
  1210. Xdefine
  1211. Xrandreseed64(seed)
  1212. X{
  1213. X    local ret;            /* return value */
  1214. X    local a;            /* generator 0 multiplier */
  1215. X    local c;            /* generator 0 adder */
  1216. X
  1217. X    /* firewall */
  1218. X    if (!isint(seed)) {
  1219. X    quit "bad args: seed must be an integer";
  1220. X    }
  1221. X    if (seed < 0) {
  1222. X    quit "bad arg: seed < 0 is reserved for future use";
  1223. X    }
  1224. X
  1225. X    /* if seed is 0, we will return 0 */
  1226. X    if (seed == 0) {
  1227. X    return (0);
  1228. X    }
  1229. X
  1230. X    /*
  1231. X     * process the low 64 bits of the seed
  1232. X     */
  1233. X    a = 6316878969928993981;
  1234. X    c = 1363042948800878693;
  1235. X    ret = (((seed & cry_mask)*a + c) & cry_mask);
  1236. X
  1237. X    /*
  1238. X     * Normally, the above equation would map:
  1239. X     *
  1240. X     *        f(0) == 1363042948800878693
  1241. X     *        f(10239951819489363767) == 0
  1242. X     *
  1243. X     * However, we have already forced f(0) == 0.  To preserve the
  1244. X     * 1-to-1 and onto map property, we force:
  1245. X     *
  1246. X     *        f(10239951819489363767) ==> 1363042948800878693
  1247. X     */
  1248. X    if (ret == 0) {
  1249. X    ret = c;
  1250. X    }
  1251. X
  1252. X    /* return the scrambled value */
  1253. X    return (ret);
  1254. X}
  1255. X
  1256. X
  1257. X/*
  1258. X * Initial read execution code
  1259. X */
  1260. Xcry_seed = srand(0);        /* pre-initialize the tables */
  1261. X
  1262. X
  1263. Xglobal lib_debug;
  1264. Xif (lib_debug >= 0) {
  1265. X    print "ver: 10.5 06:19:34 5/9/93";
  1266. X    print "shufrand() defined";
  1267. X    print "sshufrand(seed) defined";
  1268. X    print "rand([a, [b]]) defined";
  1269. X    print "srand(seed) defined";
  1270. X    print "cryrand([a, [b]]) defined";
  1271. X    print "scryrand([seed, [len1, len2]]) defined";
  1272. X    print "scryrand(seed, ip, iq, ir) defined";
  1273. X    print "random([a, [b]]) defined";
  1274. X    print "srandom(seed) defined";
  1275. X    print "obj cryobj defined";
  1276. X    print "randstate([cryobj | 0]) defined";
  1277. X    print "nxtprime(n, [val, modulus]) defined";
  1278. X}
  1279. SHAR_EOF
  1280. echo "File calc2.9.0/lib/cryrand.cal is complete"
  1281. chmod 0644 calc2.9.0/lib/cryrand.cal || echo "restore of calc2.9.0/lib/cryrand.cal fails"
  1282. set `wc -c calc2.9.0/lib/cryrand.cal`;Sum=$1
  1283. if test "$Sum" != "82965"
  1284. then echo original size 82965, current size $Sum;fi
  1285. echo "x - extracting calc2.9.0/lib/deg.cal (Text)"
  1286. sed 's/^X//' << 'SHAR_EOF' > calc2.9.0/lib/deg.cal &&
  1287. X/*
  1288. X * Copyright (c) 1993 David I. Bell
  1289. X * Permission is granted to use, distribute, or modify this source,
  1290. X * provided that this copyright notice remains intact.
  1291. X *
  1292. X * Calculate in degrees, minutes, and seconds.
  1293. X */
  1294. X
  1295. Xobj dms {deg, min, sec};
  1296. X
  1297. Xdefine dms(deg, min, sec)
  1298. X{
  1299. X    local ans;
  1300. X
  1301. X    if (isnull(sec))
  1302. X        sec = 0;
  1303. X    if (isnull(min))
  1304. X        min = 0;
  1305. X    obj dms ans;
  1306. X    ans.deg = deg;
  1307. X    ans.min = min;
  1308. X    ans.sec = sec;
  1309. X    fixdms(&ans);
  1310. X    return ans;
  1311. X}
  1312. X
  1313. X
  1314. Xdefine dms_add(a, b)
  1315. X{
  1316. X    local obj dms    ans;
  1317. X
  1318. X    ans.deg = 0;
  1319. X    ans.min = 0;
  1320. X    ans.sec = 0;
  1321. X    if (istype(a, ans)) {
  1322. X        ans.deg += a.deg;
  1323. X        ans.min += a.min;
  1324. X        ans.sec += a.sec;
  1325. X    } else
  1326. X        ans.deg += a;
  1327. X    if (istype(b, ans)) {
  1328. X        ans.deg += b.deg;
  1329. X        ans.min += b.min;
  1330. X        ans.sec += b.sec;
  1331. X    } else
  1332. X        ans.deg += b;
  1333. X    fixdms(&ans);
  1334. X    return ans;    
  1335. X}
  1336. X
  1337. X
  1338. Xdefine dms_neg(a)
  1339. X{
  1340. X    local obj dms    ans;
  1341. X
  1342. X    ans.deg = -ans.deg;
  1343. X    ans.min = -ans.min;
  1344. X    ans.sec = -ans.sec;
  1345. X    return ans;
  1346. X}
  1347. X
  1348. X
  1349. Xdefine dms_sub(a, b)
  1350. X{
  1351. X    return a - b;
  1352. X}
  1353. X
  1354. X
  1355. Xdefine dms_mul(a, b)
  1356. X{
  1357. X    local obj dms    ans;
  1358. X
  1359. X    if (istype(a, ans) && istype(b, ans))
  1360. X        quit "Cannot multiply degrees together";
  1361. X    if (istype(a, ans)) {
  1362. X        ans.deg = a.deg * b;
  1363. X        ans.min = a.min * b;
  1364. X        ans.sec = a.sec * b;
  1365. X    } else {
  1366. X        ans.deg = b.deg * a;
  1367. X        ans.min = b.min * a;
  1368. X        ans.sec = b.sec * a;
  1369. X    }
  1370. X    fixdms(&ans);
  1371. X    return ans;
  1372. X}
  1373. X
  1374. X
  1375. Xdefine dms_print(a)
  1376. X{
  1377. X    print a.deg : 'd' : a.min : 'm' : a.sec : 's' :;
  1378. X}
  1379. X
  1380. X
  1381. Xdefine dms_abs(a)
  1382. X{
  1383. X    return a.deg + a.min / 60 + a.sec / 3600;
  1384. X}
  1385. X
  1386. X
  1387. Xdefine fixdms(a)
  1388. X{
  1389. X    a.min += frac(a.deg) * 60;
  1390. X    a.deg = int(a.deg);
  1391. X    a.sec += frac(a.min) * 60;
  1392. X    a.min = int(a.min);
  1393. X    a.min += a.sec // 60;
  1394. X    a.sec %= 60;
  1395. X    a.deg += a.min // 60;
  1396. X    a.min %= 60;
  1397. X    a.deg %= 360;
  1398. X}
  1399. X
  1400. Xglobal lib_debug;
  1401. Xif (lib_debug >= 0) {
  1402. X    print "obj dms {deg, min, sec} defined";
  1403. X    print "dms(deg, min, sec) defined";
  1404. X    print "dms_add(a, b) defined";
  1405. X    print "dms_neg(a) defined";
  1406. X    print "dms_sub(a, b) defined";
  1407. X    print "dms_mul(a, b) defined";
  1408. X    print "dms_print(a) defined";
  1409. X    print "dms_abs(a) defined";
  1410. X}
  1411. SHAR_EOF
  1412. chmod 0644 calc2.9.0/lib/deg.cal || echo "restore of calc2.9.0/lib/deg.cal fails"
  1413. set `wc -c calc2.9.0/lib/deg.cal`;Sum=$1
  1414. if test "$Sum" != "1946"
  1415. then echo original size 1946, current size $Sum;fi
  1416. echo "x - extracting calc2.9.0/lib/ellip.cal (Text)"
  1417. sed 's/^X//' << 'SHAR_EOF' > calc2.9.0/lib/ellip.cal &&
  1418. X/*
  1419. X * Copyright (c) 1993 David I. Bell
  1420. X * Permission is granted to use, distribute, or modify this source,
  1421. X * provided that this copyright notice remains intact.
  1422. X *
  1423. X * Attempt to factor numbers using elliptic functions.
  1424. X *     y^2 = x^3 + a*x + b   (mod N).
  1425. X *
  1426. X * Many points (x,y) (mod N) are found that solve the above equation,
  1427. X * starting from a trivial solution and 'multiplying' that point together
  1428. X * to generate high powers of the point, looking for such a point whose
  1429. X * order contains a common factor with N.  The order of the group of points
  1430. X * varies almost randomly within a certain interval for each choice of a
  1431. X * and b, and thus each choice provides an independent opportunity to
  1432. X * factor N.  To generate a trivial solution, a is chosen and then b is
  1433. X * selected so that (1,1) is a solution.  The multiplication is done using
  1434. X * the basic fact that the equation is a cubic, and so if a line hits the
  1435. X * curve in two rational points, then the third intersection point must
  1436. X * also be rational.  Thus by drawing lines between known rational points
  1437. X * the number of rational solutions can be made very large.  When modular
  1438. X * arithmetic is used, solving for the third point requires the taking of a
  1439. X * modular inverse (instead of division), and if this fails, then the GCD
  1440. X * of the failing value and N provides a factor of N.  This description is
  1441. X * only an approximation, read "A Course in Number Theory and Cryptography"
  1442. X * by Neal Koblitz for a good explanation.
  1443. X *
  1444. X * factor(iN, ia, B, force)
  1445. X *    iN is the number to be factored.
  1446. X *    ia is the initial value of a in the equation, and each successive
  1447. X *    value of a is an independent attempt at factoring (default 1).
  1448. X *    B is the limit of the primes that make up the high power that the
  1449. X *    point is raised to for each factoring attempt (default 100).
  1450. X *    force is a flag to attempt to factor numbers even if they are
  1451. X *    thought to already be prime (default FALSE).
  1452. X *
  1453. X * Making B larger makes the power the point being raised to contain more
  1454. X * prime factors, thus increasing the chance that the order of the point
  1455. X * will be made up of those factors.  The higher B is then, the greater
  1456. X * the chance that any individual attempt will find a factor.  However,
  1457. X * a higher B also slows down the number of independent functions being
  1458. X * examined.  The order of the point for any particular function might
  1459. X * contain a large prime and so won't succeed even for a really large B,
  1460. X * whereas the next function might have an order which is quickly found.
  1461. X * So you want to trade off the depth of a particular search with the
  1462. X * number of searches made.  For example, for factoring 30 digits, I make
  1463. X * B be about 1000 (probably still too small).
  1464. X *
  1465. X * If you have lots of machines available, then you can run parallel
  1466. X * factoring attempts for the same number by giving different starting
  1467. X * values of ia for each machine (e.g. 1000, 2000, 3000).
  1468. X *
  1469. X * The output as the function is running is (occasionally) the value of a
  1470. X * when a new function is started, the prime that is being included in the
  1471. X * high power being calculated, and the current point which is the result
  1472. X * of the powers so far.
  1473. X *
  1474. X * If a factor is found, it is returned and is also saved in the global
  1475. X * variable f.  The number being factored is also saved in the global
  1476. X * variable N.
  1477. X */
  1478. X
  1479. Xobj point {x, y};
  1480. Xglobal    N;        /* number to factor */
  1481. Xglobal    a;        /* first coefficient */
  1482. Xglobal    b;        /* second coefficient */
  1483. Xglobal    f;        /* found factor */
  1484. X
  1485. X
  1486. Xdefine factor(iN, ia, B, force)
  1487. X{
  1488. X    local    C, x, p;
  1489. X
  1490. X    if (!force && ptest(iN, 50))
  1491. X        return 1;
  1492. X    if (isnull(B))
  1493. X        B = 100;
  1494. X    if (isnull(ia))
  1495. X        ia = 1;
  1496. X    obj point x;
  1497. X    a = ia;
  1498. X    b = -ia;
  1499. X    N = iN;
  1500. X    C = isqrt(N);
  1501. X    C = 2 * C + 2 * isqrt(C) + 1;
  1502. X    f = 0;
  1503. X    while (f == 0) {
  1504. X        print "A =", a;
  1505. X        x.x = 1;
  1506. X        x.y = 1;
  1507. X        print 2, x;
  1508. X        x = x ^ (2 ^ (highbit(C) + 1));
  1509. X        for (p = 3; ((p < B) && (f == 0)); p += 2) {
  1510. X            if (!ptest(p, 1))
  1511. X                continue;
  1512. X            print p, x;
  1513. X            x = x ^ (p ^ ((highbit(C) // highbit(p)) + 1));
  1514. X        }
  1515. X        a++;
  1516. X        b--;
  1517. X    }
  1518. X    return f;
  1519. X}
  1520. X
  1521. X
  1522. Xdefine point_print(p)
  1523. X{
  1524. X    print "(" : p.x : "," : p.y : ")" :;
  1525. X}
  1526. X
  1527. X
  1528. Xdefine point_mul(p1, p2)
  1529. X{
  1530. X    local    r, m;
  1531. X
  1532. X    if (p2 == 1)
  1533. X        return p1;
  1534. X    if (p1 == p2)
  1535. X        return point_square(&p1);
  1536. X    obj point r;
  1537. X    m = (minv(p2.x - p1.x, N) * (p2.y - p1.y)) % N;
  1538. X    if (m == 0) {
  1539. X        if (f == 0)
  1540. X            f = gcd(p2.x - p1.x, N);
  1541. X        r.x = 1;
  1542. X        r.y = 1;
  1543. X        return r;        
  1544. X    }
  1545. X    r.x = (m^2 - p1.x - p2.x) % N;
  1546. X    r.y = ((m * (p1.x - r.x)) - p1.y) % N;
  1547. X    return r;
  1548. X}
  1549. X
  1550. X
  1551. Xdefine point_square(p)
  1552. X{
  1553. X    local    r, m;
  1554. X
  1555. X    obj point r;
  1556. X    m = ((3 * p.x^2 + a) * minv(p.y << 1, N)) % N;
  1557. X    if (m == 0) {
  1558. X        if (f == 0)
  1559. X            f = gcd(p.y << 1, N);
  1560. X        r.x = 1;
  1561. X        r.y = 1;
  1562. X        return r;
  1563. X    }
  1564. X    r.x = (m^2 - p.x - p.x) % N;
  1565. X    r.y = ((m * (p.x - r.x)) - p.y) % N;
  1566. X    return r;
  1567. X}
  1568. X
  1569. X
  1570. Xdefine point_pow(p, pow)
  1571. X{
  1572. X    local bit, r, t;
  1573. X
  1574. X    r = 1;
  1575. X    if (isodd(pow))
  1576. X        r = p;
  1577. X    t = p;
  1578. X    for (bit = 2; ((bit <= pow) && (f == 0)); bit <<= 1) {
  1579. X        t = point_square(&t);
  1580. X        if (bit & pow)
  1581. X            r = point_mul(&t, &r);
  1582. X    }
  1583. X    return r;
  1584. X}
  1585. X
  1586. Xglobal lib_debug;
  1587. Xif (lib_debug >= 0) {
  1588. X    print "factor(N, I, B, force) defined";
  1589. X}
  1590. SHAR_EOF
  1591. chmod 0644 calc2.9.0/lib/ellip.cal || echo "restore of calc2.9.0/lib/ellip.cal fails"
  1592. set `wc -c calc2.9.0/lib/ellip.cal`;Sum=$1
  1593. if test "$Sum" != "5017"
  1594. then echo original size 5017, current size $Sum;fi
  1595. echo "x - extracting calc2.9.0/lib/lucas.cal (Text)"
  1596. sed 's/^X//' << 'SHAR_EOF' > calc2.9.0/lib/lucas.cal &&
  1597. X/*
  1598. X * Copyright (c) 1993 Landon Curt Noll
  1599. X * Permission is granted to use, distribute, or modify this source,
  1600. X * provided that this copyright notice remains intact.
  1601. X *
  1602. X * By: Landon Curt Noll
  1603. X *     chongo@toad.com  -or-  ...!{pyramid,sun,uunet}!hoptoad!chongo
  1604. X *
  1605. X *
  1606. X * lucas - perform a Lucas primality test on h*2^n-1
  1607. X *
  1608. X * HISTORICAL NOTE:
  1609. X *
  1610. X * On 6 August 1989 at 00:53 PDT, the 'Amdahl 6', a team consisting of
  1611. X * John Brown, Landon Curt Noll, Bodo Parady, Gene Smith, Joel Smith and
  1612. X * Sergio Zarantonello proved the following 65087 digit number to be prime:
  1613. X *
  1614. X *                  216193
  1615. X *            391581 * 2      -1
  1616. X *
  1617. X * At the time of discovery, this number was the largest known prime.
  1618. X * The primality was demonstrated by a program implementing the test
  1619. X * found in these routines.  An Amdahl 1200 takes 1987 seconds to test
  1620. X * the primality of this number.  A Cray 2 took several hours to
  1621. X * confirm this prime.  As of 28 Aug 1993, this prime was the 2nd
  1622. X * largest known prime and the largest known non-Mersenne prime.
  1623. X *
  1624. X * The same team also discovered the following twin prime pair:
  1625. X *
  1626. X *               11235           11235
  1627. X *        1706595 * 2     -1    1706595 * 2     +1
  1628. X *
  1629. X * As of 28 Aug 1993, these primes was still the largest known twin prime pair.
  1630. X *
  1631. X * ON GAINING A WORLD RECORD:
  1632. X *
  1633. X * The routines in calc were designed to be portable, and to work on
  1634. X * numbers of 'sane' size.  The Amdahl 6 team used a 'ultra-high speed 
  1635. X * multi-precision' package that a machine dependent collection of routines 
  1636. X * tuned for a long trace vector processor to work with very large numbers.
  1637. X * The heart of the package was a multiplication and square routine that 
  1638. X * was based on the PFA Fast Fourier Transform and on Winograd's radix FFTs.
  1639. X *
  1640. X * Having a fast computer, and a good multi-precision package are
  1641. X * critical, but one also needs to know where to look in order to have
  1642. X * a good chance at a record.  Knowing what to test is beyond the scope
  1643. X * of this routine.  However the following observations are noted:
  1644. X *
  1645. X *    test numbers of the form h*2^n-1
  1646. X *    fix a value of n and vary the value h
  1647. X *    n mod 128 == 0
  1648. X *    h*2^n-1 is not divisible by any small prime < 2^40
  1649. X *    0 < h < 2^39
  1650. X *    h*2^n+1 is not divisible by any small prime < 2^40
  1651. X *
  1652. X * The Mersenne test for '2^n-1' is the fastest known primality test
  1653. X * for a given large numbers.  However, it is faster to search for
  1654. X * primes of the form 'h*2^n-1'.  When n is around 20000, one can find
  1655. X * a prime of the form 'h*2^n-1' in about 1/2 the time.
  1656. X *
  1657. X * Critical to understanding why 'h*2^n-1' is to observe that primes of
  1658. X * the form '2^n-1' seem to bunch around "islands".  Such "islands"
  1659. X * seem to be getting fewer and farther in-between, forcing the time
  1660. X * for each test to grow longer and longer (worse then O(n^2 log n)).
  1661. X * On the other hand, when one tests 'h*2^n-1', fixes 'n' and varies
  1662. X * 'h', the time to test each number remains relatively constant.
  1663. X *
  1664. X * It is clearly a win to eliminate potential test candidates by
  1665. X * rejecting numbers that that are divisible by 'small' primes.  We
  1666. X * (the "Amdahl 6") rejected all numbers that were divisible by primes
  1667. X * less than '2^40'.  We stopped looking for small factors at '2^40'
  1668. X * when the rate of candidates being eliminated was slowed down to
  1669. X * just a trickle.
  1670. X *
  1671. X * The 'n mod 128 == 0' restriction allows one to test for divisibility
  1672. X * of small primes more quickly.  To test of 'q' is a factor of 'k*2^n-1',
  1673. X * one check to see if 'k*2^n mod q' == 1, which is the same a checking
  1674. X * if 'h*(2^n mod q) mod q' == 1.  One can compute '2^n mod q' by making
  1675. X * use of the following:
  1676. X *
  1677. X *    if
  1678. X *        y = 2^x mod q
  1679. X *    then
  1680. X *        2^(2x) mod q   == y^2 mod q        0 bit
  1681. X *        2^(2x+1) mod q == 2*y^2 mod q        1 bit
  1682. X *
  1683. X * The choice of which expression depends on the binary pattern of 'n'.
  1684. X * Since '1' bits require an extra step (multiply by 2), one should
  1685. X * select value of 'n' that contain mostly '0' bits.  The restriction
  1686. X * of 'n mod 128 == 0' ensures that the bottom 7 bits of 'n' are 0.
  1687. X *
  1688. X * By limiting 'h' to '2^39' and eliminating all values divisible by
  1689. X * small primes < twice the 'h' limit (2^40), one knows that all
  1690. X * remaining candidates are relatively prime.  Thus, when a candidate
  1691. X * is proven to be composite (not prime) by the big test, one knows
  1692. X * that the factors for that number (whatever they may be) will not
  1693. X * be the factors of another candidate.
  1694. X *
  1695. X * Finally, one should eliminate all values of 'h*2^n-1' where
  1696. X * 'h*2^n+1' is divisible by a small primes.  The ideas behind this 
  1697. X * point is beyond the scope of this program.
  1698. X */
  1699. X
  1700. Xglobal pprod256;    /* product of  "primes up to 256" / "primes up to 46" */
  1701. Xglobal lib_debug;    /* 1 => print debug statements */
  1702. X
  1703. X/*
  1704. X * lucas - lucas primality test on h*2^n-1
  1705. X *
  1706. X * ABOUT THE TEST:
  1707. X *
  1708. X * This routine will perform a primality test on h*2^n-1 based on
  1709. X * the mathematics of Lucas, Lehmer and Riesel.  One should read
  1710. X * the following article:
  1711. X *
  1712. X * Ref1:
  1713. X *    "Lucasian Criteria for the Primality of N=h*2^n-1", by Hans Riesel,
  1714. X *    Mathematics of Computation, Vol 23 #108, pp. 869-875, Oct 1969
  1715. X *
  1716. X * The following book is also useful:
  1717. X *
  1718. X * Ref2:
  1719. X *    "Prime numbers and Computer Methods for Factorization", by Hans Riesel,
  1720. X *    Birkhauser, 1985, pp 131-134, 278-285, 438-444
  1721. X *
  1722. X * A few useful Legendre identities may be found in:
  1723. X *
  1724. X * Ref3:
  1725. X *    "Introduction to Analytic Number Theory", by Tom A. Apostol,
  1726. X *    Springer-Verlag, 1984, p 188.
  1727. X *
  1728. X * This test is performed as follows:    (see Ref1, Theorem 5)
  1729. X *
  1730. X *    a) generate u(0)         (see the function gen_u0() below)
  1731. X *
  1732. X *    b) generate u(n-2) according to the rule:
  1733. X *
  1734. X *        u(i+1) = u(i)^2-2 mod h*2^n-1
  1735. X *
  1736. X *    c) h*2^n-1 is prime if and only if u(n-2) == 0        Q.E.D. :-)
  1737. X *
  1738. X * Now the following conditions must be true for the test to work:
  1739. X *
  1740. X *      n >= 2
  1741. X *    h >= 1
  1742. X *      h < 2^n
  1743. X *    h mod 2 == 1
  1744. X *
  1745. X * A few misc notes:
  1746. X *
  1747. X * In order to reduce the number of tests, as attempt to eliminate
  1748. X * any number that is divisible by a prime less than 257.  Valid prime
  1749. X * candidates less than 257 are declared prime as a special case.
  1750. X *
  1751. X * The condition 'h mod 2 == 1' is not a problem.  Say one is testing
  1752. X * 'j*2^m-1', where j is even.  If we note that:
  1753. X *
  1754. X *      j mod 2^x == 0 for x>0   implies   j*2^m-1 == ((j/2^x)*2^(m+x))-1,
  1755. X *
  1756. X * then we can let h=j/2^x and n=m+x and test 'h*2^n-1' which is the value.
  1757. X * We need only consider odd values of h because we can rewrite our numbers
  1758. X * do make this so.
  1759. X *
  1760. X * input:
  1761. X *    h    the h as in h*2^n-1
  1762. X *    n    the n as in h*2^n-1
  1763. X *
  1764. X * returns:
  1765. X *    1 => h*2^n-1 is prime
  1766. X *    0 => h*2^n-1 is not prime
  1767. X *     -1 => a test could not be formed, or h >= 2^n, h <= 0, n <= 0
  1768. X */
  1769. Xdefine
  1770. Xlucas(h, n)
  1771. X{
  1772. X    local testval;        /* h*2^n-1 */
  1773. X    local shiftdown;    /* the power of 2 that divides h */
  1774. X    local u;        /* the u(i) sequence value */
  1775. X    local v1;        /* the v(1) generator of u(0) */
  1776. X    local i;        /* u sequence cycle number */
  1777. X    local oldh;        /* pre-reduced h */
  1778. X    local oldn;        /* pre-reduced n */
  1779. X    local bits;        /* highbit of h*2^n-1 */
  1780. X
  1781. X    /*
  1782. X     * check arg types
  1783. X     */
  1784. X    if (!isint(h)) {
  1785. X        ldebug("lucas", "h is non-int");
  1786. X        quit "FATAL: bad args: h must be an integer";
  1787. X    }
  1788. X    if (!isint(n)) {
  1789. X        ldebug("lucas", "n is non-int");
  1790. X        quit "FATAL: bad args: n must be an integer";
  1791. X    }
  1792. X
  1793. X    /*
  1794. X     * reduce h if even
  1795. X     *
  1796. X     * we will force h to be odd by moving powers of two over to 2^n
  1797. X     */
  1798. X    oldh = h;
  1799. X    oldn = n;
  1800. X    shiftdown = fcnt(h,2);  /* h % 2^shiftdown == 0, max shiftdown */
  1801. X    if (shiftdown > 0) {
  1802. X        h >>= shiftdown;
  1803. X        n += shiftdown;
  1804. X    }
  1805. X
  1806. X    /*
  1807. X     * enforce the 0 < h < 2^n rule
  1808. X     */
  1809. X    if (h <= 0 || n <= 0) {
  1810. X        print "ERROR: reduced args violate the rule: 0 < h < 2^n";
  1811. X        print "    ERROR: h=":oldh, "n=":oldn, "reduced h=":h, "n=":n;
  1812. X        ldebug("lucas", "unknown: h <= 0 || n <= 0");
  1813. X        return -1;
  1814. X    }
  1815. X    if (highbit(h) >= n) {
  1816. X        print "ERROR: reduced args violate the rule: h < 2^n";
  1817. X        print "    ERROR: h=":oldh, "n=":oldn, "reduced h=":h, "n=":n;
  1818. X        ldebug("lucas", "unknown: highbit(h) >= n");
  1819. X        return -1;
  1820. X    }
  1821. X
  1822. X    /*
  1823. X     * catch the degenerate case of h*2^n-1 == 1
  1824. X     */
  1825. X    if (h == 1 && n == 1) {
  1826. X        ldebug("lucas", "not prime: h == 1 && n == 1");
  1827. X        return 0;    /* 1*2^1-1 == 1 is not prime */
  1828. X    }
  1829. X
  1830. X    /*
  1831. X     * catch the degenerate case of n==2
  1832. X     *
  1833. X     * n==2 and 0<h<2^n  ==>  0<h<4
  1834. X     *
  1835. X     * Since h is now odd  ==>  h==1 or h==3
  1836. X     */
  1837. X    if (h == 1 && n == 2) {
  1838. X        ldebug("lucas", "prime: h == 1 && n == 2");
  1839. X        return 1;    /* 1*2^2-1 == 3 is prime */
  1840. X    }
  1841. X    if (h == 3 && n == 2) {
  1842. X        ldebug("lucas", "prime: h == 3 && n == 2");
  1843. X        return 1;    /* 3*2^2-1 == 11 is prime */
  1844. X    }
  1845. X
  1846. X    /*
  1847. X     * catch small primes < 257
  1848. X     *
  1849. X     * We check for only a few primes because the other primes < 257
  1850. X     * violate the checks above.
  1851. X     */
  1852. X    if (h == 1) {
  1853. X        if (n == 3 || n == 5 || n == 7) {
  1854. X            ldebug("lucas", "prime: 3, 7, 31, 127 are prime");
  1855. X            return 1;    /* 3, 7, 31, 127 are prime */
  1856. X        }
  1857. X    }
  1858. X    if (h == 3) {
  1859. X        if (n == 2 || n == 3 || n == 4 || n == 6) {
  1860. X            ldebug("lucas", "prime: 11, 23, 47, 191 are prime");
  1861. X            return 1;    /* 11, 23, 47, 191 are prime */
  1862. X        }
  1863. X    }
  1864. X    if (h == 5 && n == 4) {
  1865. X        ldebug("lucas", "prime: 79 is prime");
  1866. X        return 1;        /* 79 is prime */
  1867. X    }
  1868. X    if (h == 7 && n == 5) {
  1869. X        ldebug("lucas", "prime: 223 is prime");
  1870. X        return 1;        /* 223 is prime */
  1871. X    }
  1872. X    if (h == 15 && n == 4) {
  1873. X        ldebug("lucas", "prime: 239 is prime");
  1874. X        return 1;        /* 239 is prime */
  1875. X    }
  1876. X
  1877. X    /*
  1878. X     * Avoid any numbers divisible by small primes
  1879. X     */
  1880. X    /*
  1881. X     * check for 3 <= prime factors < 29
  1882. X     * pfact(28)/2 = 111546435
  1883. X     */
  1884. X    testval = h*2^n - 1;
  1885. X    if (gcd(testval, 111546435) > 1) {
  1886. X        /* a small 3 <= prime < 29 divides h*2^n-1 */
  1887. X        ldebug("lucas","not-prime: 3<=prime<29 divides h*2^n-1");
  1888. X        return 0;
  1889. X    }
  1890. X    /*
  1891. X     * check for 29 <= prime factors < 47
  1892. X     * pfact(46)/pfact(28) = 5864229
  1893. X     */
  1894. X    if (gcd(testval, 58642669) > 1) {
  1895. X        /* a small 29 <= prime < 47 divides h*2^n-1 */
  1896. X        ldebug("lucas","not-prime: 29<=prime<47 divides h*2^n-1");
  1897. X        return 0;
  1898. X    }
  1899. X    /*
  1900. X     * check for prime 47 <= factors < 257, if h*2^n-1 is large
  1901. X     * 2^282 > pfact(256)/pfact(46) > 2^281
  1902. X     */
  1903. X    bits = highbit(testval);
  1904. X    if (bits >= 281) {
  1905. X        if (pprod256 <= 0) {
  1906. X            pprod256 = pfact(256)/pfact(46);
  1907. X        }
  1908. X        if (gcd(testval, pprod256) > 1) {
  1909. X            /* a small 47 <= prime < 257 divides h*2^n-1 */
  1910. X            ldebug("lucas",\
  1911. X                "not-prime: 47<=prime<257 divides h*2^n-1");
  1912. X            return 0;
  1913. X        }
  1914. X    }
  1915. X
  1916. X    /*
  1917. X     * try to compute u(0)
  1918. X     *
  1919. X     * We will use gen_v1() to give us a v(1) using the values
  1920. X     * of 'h' and 'n'.  We will then use gen_u0() to convert
  1921. X     * the v(1) into u(0).
  1922. X     *
  1923. X     * If gen_v1() returns a negative value, then we failed to
  1924. X     * generate a test for h*2^n-1.  This is because h mod 3 == 0
  1925. X     * is hard to do, and in rare cases, exceed the tables found
  1926. X     * in this program.  We will generate an message and assume
  1927. X     * the number is not prime, even though if we had a larger
  1928. X     * table, we might have been able to show that it is prime.
  1929. X     */
  1930. X    v1 = gen_v1(h, n, testval);
  1931. X    if (v1 < 0) {
  1932. X        /* failure to test number */
  1933. X        print "unable to compute v(1) for", h : "*2^" : n : "-1";
  1934. X        ldebug("lucas", "unknown: no v(1)");
  1935. X        return -1;
  1936. X    }
  1937. X    u = gen_u0(h, n, testval, v1);
  1938. X
  1939. X    /*
  1940. X     * compute u(n-2)
  1941. X     */
  1942. X    for (i=3; i <= n; ++i) {
  1943. X        u = (u^2 - 2) % testval;
  1944. X    }
  1945. X
  1946. X    /*
  1947. X     * return 1 if prime, 0 is not prime
  1948. X     */
  1949. X    if (u == 0) {
  1950. X        ldebug("lucas", "prime: end of test");
  1951. X        return 1;
  1952. X    } else {
  1953. X        ldebug("lucas", "not-prime: end of test");
  1954. X        return 0;
  1955. X    }
  1956. X}
  1957. X
  1958. X/*
  1959. X * gen_u0 - determine the initial Lucas sequence for h*2^n-1
  1960. X *
  1961. X * According to Ref1, Theorem 5:
  1962. X *
  1963. X *    u(0) = alpha^h + alpha^(-h)
  1964. X *
  1965. X * Now:
  1966. X *
  1967. X *    v(x) = alpha^x + alpha^(-x)    (Ref1, bottom of page 872)
  1968. X *
  1969. X * Therefore:
  1970. X *
  1971. X *    u(0) = v(h)
  1972. X *
  1973. X * We calculate v(h) as follows:    (Ref1, top of page 873)
  1974. X *
  1975. X *    v(0) = alpha^0 + alpha^(-0) = 2
  1976. X *    v(1) = alpha^1 + alpha^(-1) = gen_v1(h,n)
  1977. X *    v(n+2) = v(1)*v(n+1) - v(n)
  1978. X *
  1979. X * This function does not concern itself with the value of 'alpha'.
  1980. X * The gen_v1() function is used to compute v(1), and identity
  1981. X * functions take it from there.
  1982. X *
  1983. X * It can be shown that the following are true:
  1984. X *
  1985. X *    v(2*n) = v(n)^2 - 2
  1986. X *    v(2*n+1) = v(n+1)*v(n) - v(1)
  1987. X *
  1988. X * To prevent v(x) from growing too large, one may replace v(x) with
  1989. X * `v(x) mod h*2^n-1' at any time.
  1990. X *
  1991. X * See the function gen_v1() for details on the value of v(1).
  1992. X *
  1993. X * input:
  1994. X *    h    - h as in h*2^n-1    (h mod 2 != 0)
  1995. X *    n    - n as in h*2^n-1
  1996. X *    testval    - h*2^n-1
  1997. X *    v1    - gen_v1(h,n)        (see function below)
  1998. X *
  1999. X * returns:
  2000. X *    u(0)    - initial value for Lucas test on h*2^n-1
  2001. X *    -1    - failed to generate u(0)
  2002. X */
  2003. Xdefine
  2004. Xgen_u0(h, n, testval, v1)
  2005. X{
  2006. X    local shiftdown;    /* the power of 2 that divides h */
  2007. X    local r;        /* low value: v(n) */
  2008. X    local s;        /* high value: v(n+1) */
  2009. X    local hbits;        /* highest bit set in h */
  2010. X    local i;
  2011. X
  2012. X    /*
  2013. X     * check arg types
  2014. X     */
  2015. X    if (!isint(h)) {
  2016. X        quit "bad args: h must be an integer";
  2017. X    }
  2018. X    if (!isint(n)) {
  2019. X        quit "bad args: n must be an integer";
  2020. X    }
  2021. X    if (!isint(testval)) {
  2022. SHAR_EOF
  2023. echo "End of part 17"
  2024. echo "File calc2.9.0/lib/lucas.cal is continued in part 18"
  2025. echo "18" > s2_seq_.tmp
  2026. exit 0
  2027.