Advertisement
hpolzer

Middle square method (PRNG)

Mar 29th, 2016
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.06 KB | None | 0 0
  1. /*
  2.     middle_square_method.c computes pseudorandom numbers starting with a number
  3.     given at the command line. (Outdated method, for educational purposes only.
  4.     Try 9319 or 12314.) To compile run "gcc -ansi -o msm middle_square_method.c".
  5.     Copyright (C) <February 29, 2016> Henning Polzer,
  6.     send comments and error reports to: h underscore polzer at gmx dot de.
  7.  
  8.     This program is free software; you can redistribute it and/or
  9.     modify it under the terms of the GNU General Public License
  10.     as published by the Free Software Foundation; either version 2
  11.     of the License, or (at your option) any later version.
  12.  
  13.     This program is distributed in the hope that it will be useful,
  14.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.     GNU General Public License for more details.
  17.  
  18.     You should have received a copy of the GNU General Public License
  19.     along with this program; if not, write to the Free Software
  20.     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
  21. */
  22.  
  23.  
  24. #include <math.h>           /* fabs(), floor(), log10(), pow() */
  25. #include <stdio.h>          /* printf(), scanf() */
  26. #include <stdlib.h>         /* atol() */
  27.  
  28. #define OBERGRENZE 50       /* für sicheren Programmabruch, willkuerlich gesetzt */
  29.  
  30. typedef unsigned long ganzzahl;
  31.  
  32. ganzzahl stellen (wert)     /* Stellenzahl ermitteln */
  33. {
  34.     if (wert != 0) return floor (log10(fabs(wert)))+1; else return 1;
  35. }
  36.  
  37. ganzzahl qmg (z)
  38. {
  39.     ganzzahl quadrat=z*z, diff=stellen(quadrat)-stellen(z), links=floor(diff/2), t;
  40.  
  41.     if (z < 4) return 0;
  42.     quadrat=floor(quadrat/powl(10,diff-links));
  43.     t=pow(10,stellen(quadrat)-links);
  44.     return quadrat%t;
  45. }
  46.  
  47. int main (int argc, char *argv[])
  48. {
  49.     ganzzahl erg, i=1, z, verlassen=0;
  50.  
  51.     if (((argc==2) && (z = fabs(atol(argv[1])))) != 0) {
  52.       do {
  53.         erg = qmg (z);
  54.         if (erg == z) verlassen=1;
  55.         z = erg;
  56.         printf ("%ld ", erg);
  57.             i += 1;
  58.       } while ((verlassen==0) && (erg != 0) && (i < OBERGRENZE));
  59.       printf ("\n");
  60.     } else printf ("Aufruf: qmg eine_zahl_groesser_null\n");
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement