Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Alexandru Scvortov

« Newer Snippets
Older Snippets »
Showing 31-40 of 50 total

Writeln in assembler

NASM code for writing the integer in eax to stdout.

   1  
   2  segment .bss
   3          writeTemp       resb    10
   4  
   5  segment .text
   6  _writeln:                               
   7          MOV     ebx,    eax             ; Number is already in eax
   8          MOV     ecx,    10
   9          XOR     edi,    edi
  10  L0:
  11          CMP     eax,    0
  12          JE      L1
  13          ADD     edi,    1
  14          XOR     edx,    edx
  15          IDIV    ecx
  16          JMP     L0
  17  L1:
  18          ADD     edi,    writeTemp       ; Length of the number is in edi
  19          MOV     esi,    edi
  20          MOV byte        [edi],  10      ; Add a newline
  21          SUB     edi,    1
  22          XOR     eax,    eax
  23  L2:                             
  24          CMP     ebx,    0
  25          JE      L3
  26          MOV     eax,    ebx
  27          XOR     edx,    edx
  28          IDIV    ecx
  29          ADD     dl,     48
  30          MOV     [edi],  dl
  31          SUB     edi,    1
  32          MOV     ebx,    eax
  33          JMP     L2                      ; Number has been written to writeTemp from tail to head
  34  L3:                             
  35          MOV     eax,    4
  36          MOV     ebx,    1
  37          MOV     ecx,    writeTemp
  38          MOV     edx,    esi
  39          SUB     edx,    writeTemp
  40          ADD     edx,    1
  41          INT     80h

Square root in Scheme

This implements a square root function in Scheme using Newton's approximation algorithm.

Basically, if you want the square root of y and your best guess is x, a better guess is the average of x and y/x.

So, if you want the square root of 10 and your best guess is 3,
x=3 y=10 x<-(3 + 10/3)/2
x=3.166 y=10 x<-(3.166 + 10/3.133)/2
x=3.162
...

   1  
   2  (define (sqrt-iter guess x)
   3      (if (good-enough? guess x)
   4          guess
   5          (sqrt-iter (improve guess x)
   6                      x)))
   7  
   8  (define (improve guess x)
   9      (average guess (/ x guess)))
  10  
  11  (define (average x y)
  12      (/ (+ x y) 2))
  13  
  14  (define (good-enough? guess x)
  15      (< (abs (- (square guess) x))
  16          0.001))
  17  
  18  (define (sqrt x)
  19      (sqrt-iter 1.0 x))
  20  
  21  (sqrt 10)


Simple integer expression interpreter

This is a simple integer expression interpreter.

   1  
   2  #include <iostream>
   3  #include <string>
   4  #include <map>
   5  #include <cctype>
   6  
   7  char look;
   8  std::map<std::string, int> table;
   9  
  10  void getChar() {
  11      look = std::cin.get();
  12  }
  13  
  14  void error(const std::string &s) {
  15      std::cout << std::endl;
  16      std::cout << "Error: " << s << "." << std::endl;
  17  }
  18  
  19  void abort(const std::string &s) {
  20      error(s);
  21      exit(1);
  22  }
  23  
  24  void expected(const std::string &s) {
  25      abort(s + " Expected");
  26  }
  27  
  28  bool isAlpha(char c) {
  29      return isalpha(c);
  30  }
  31  
  32  bool isDigit(char c) {
  33      return isdigit(c);
  34  }
  35  
  36  bool isAlNum(char c) {
  37      return isalnum(c);
  38  }
  39  
  40  bool isAddop(char c) {
  41      return ((c == '+') || (c == '-'));
  42  }
  43  
  44  bool isMulop(char c) {
  45      return (('*' == c) || ('/' == c));
  46  }
  47  
  48  bool isWhite(char c) {
  49      return ((' ' == c) || ('\t' == c));
  50  }
  51  
  52  void skipWhite() {
  53      while (isWhite(look))
  54          getChar();
  55  }
  56  
  57  void match(char x) {
  58      if (look != x)
  59          expected(std::string("\"") + x + "\"");
  60      else {
  61          getChar();
  62          skipWhite();
  63      }
  64  }
  65  
  66  void emit(const std::string &s) {
  67      std::cout << "\t"  << s;
  68  }
  69  
  70  void emitLn(const std::string &s) {
  71      emit(s);
  72      std::cout << std::endl;
  73  }
  74  
  75  void newLine() {
  76      if (look == '\n')
  77          getChar();
  78  }
  79  
  80  std::string getName() {
  81      if (!isAlpha(look))
  82          expected("Name");
  83  
  84      std::string name;
  85      while (isAlNum(look)) {
  86          name += look;
  87          getChar();
  88      }
  89      skipWhite();
  90  
  91      return name;
  92  }
  93  
  94  int getNum() {
  95      int value(0);
  96  
  97      if (!isDigit(look))
  98          expected("Integer");
  99  
 100      while (isDigit(look)) {
 101          value = value * 10 + look - '0';
 102          getChar();
 103      }
 104      skipWhite();
 105  
 106      return value;
 107  }
 108  
 109  int expression();
 110  
 111  int factor() {
 112      int ret;
 113  
 114      if (look == '(') {
 115          match('(');
 116          ret = expression();
 117          match(')');
 118      } else if (isAlpha(look)) {
 119          std::string name = getName();
 120          if (table.count(name) == 0)
 121              table.insert(std::pair<std::string, int>(name, 0));
 122          ret = table[name];
 123      } else
 124          ret = getNum();
 125  
 126      return ret;
 127  }
 128  
 129  int term() {
 130      int value = factor();
 131  
 132      while (isMulop(look)) {
 133          if (look == '*') {
 134              match('*');
 135              value *= factor();
 136          } else if (look == '/') {
 137              match('/');
 138              value /= factor();
 139          }
 140      }
 141  
 142      return value;
 143  }
 144  
 145  int expression() {
 146      int value(0);
 147  
 148      if (!isAddop(look))
 149          value = term();
 150  
 151      while (isAddop(look)) {
 152          if (look == '+') {
 153              match('+');
 154              value += term();
 155          } else if (look == '-') {
 156              match('-');
 157              value -= term();
 158          }
 159      }
 160  
 161      return value;
 162  }
 163  
 164  void assignment() {
 165      std::string name = getName();
 166      match('=');
 167      if (table.count(name) == 1)
 168          table[name] = expression();
 169      else
 170          table.insert(std::pair<std::string, int>(name, expression()));
 171  
 172      std::cout << name << " = " << table[name] << std::endl;
 173  }
 174  
 175  void init() {
 176      getChar();
 177      skipWhite();
 178  }
 179  
 180  int main(int argc, char *argv[]) {
 181      init();
 182  
 183      do {
 184          assignment();
 185          newLine();
 186      } while ((look != '.') && (look != '\n'));
 187  
 188      return 0;
 189  }

C++ way to randomly select M numbers

This will randomly select M numbers from the interval [1, NMAX].

Note the extensive use of STL.

   1  
   2  const short NMAX = 49;
   3  const short M = 6;
   4  
   5  std::vector<short> v;
   6  for (short i(0); i < NMAX; ++i)
   7  	v.push_back(i + 1);
   8  
   9  random_shuffle(v.begin(), v.end());
  10  copy(v.begin(), v.begin() + M, std::ostream_iterator<short>(std::cout, " "));

Pollard's rho heuristic

Pollard's rho heuristic is a method used to find a number's factors. This is faster than the classic brute-force, try every number until sqrt(n) method, but it's results are highly unpredictable.

This just prints the factors.

   1  
   2  import sys
   3  import random
   4  
   5  def Euclid(a, b):
   6    while b != 0:
   7      r = a % b
   8      a = b
   9      b = r
  10    return a
  11  
  12  def PollardRho(n):
  13    i = 1
  14    x = random.randint(0, n - 1)
  15    y = x
  16    k = 2
  17    tried = set()
  18    tried.add(x)
  19    while True:
  20      i = i + 1
  21      x = (x ** 2 - 1) % n
  22      if x in tried:
  23        return
  24      tried.add(x)
  25      d = Euclid(y - x, n)
  26      if d != 1 and d != n:
  27        print d # d is a factor. Print it.
  28      if i == k:
  29        y = x
  30        k = 2 * k
  31  
  32  def main(argv):
  33    PollardRho(int(argv[0]))
  34  
  35  if __name__ == "__main__":
  36      main(sys.argv[1:])

Miller-Rabin primality test

The Miller-Rabin primality test.

MillerRabin(n, s = 1000) -> bool Checks whether n is prime or not. This is an extremley fast algorithm designed to test very large numbers.

s is the number of tests to perform. The chance that Rabin-Miller is mistaken about a number (i.e. thinks it's prime, but it's not) is 2^(-s). So, a value of 50 for s is more than enough for any imaginable goal (2^(-50) is 8.8817841970012523e-16).

   1  
   2  import sys
   3  import random
   4  
   5  def toBinary(n):
   6    r = []
   7    while (n > 0):
   8      r.append(n % 2)
   9      n = n / 2
  10    return r
  11  
  12  def test(a, n):
  13    """
  14    test(a, n) -> bool Tests whether n is complex.
  15  
  16    Returns:
  17      - True, if n is complex.
  18      - False, if n is probably prime.
  19    """
  20    b = toBinary(n - 1)
  21    d = 1
  22    for i in xrange(len(b) - 1, -1, -1):
  23      x = d
  24      d = (d * d) % n
  25      if d == 1 and x != 1 and x != n - 1:
  26        return True # Complex
  27      if b[i] == 1:
  28        d = (d * a) % n
  29    if d != 1:
  30      return True # Complex
  31    return False # Prime
  32  
  33  def MillerRabin(n, s = 50):
  34    """
  35      MillerRabin(n, s = 1000) -> bool Checks whether n is prime or not
  36  
  37      Returns:
  38        - True, if n is probably prime.
  39        - False, if n is complex.
  40    """
  41    for j in xrange(1, s + 1):
  42      a = random.randint(1, n - 1)
  43      if (test(a, n)):
  44        return False # n is complex
  45    return True # n is prime
  46  
  47  def main(argv):
  48    print MillerRabin(int(argv[0]), int(argv[1]))
  49  
  50  if __name__ == "__main__":
  51    main(sys.argv[1:])

Modular linear equation solver

Prints the roots of this equation:
ax = b (mod n)

Relies on Euclid's extended algorithm:
http://snippets.dzone.com/posts/show/4192

   1  
   2  def solveLinearModularEquation(a, b, n):
   3    d, xx, yy = euclidExtended(a, n)
   4    if (b % d == 0):
   5      x0 = (xx * (b / d)) % n
   6      for i in xrange(0, d):
   7        print (x0 + i * (n / d)) % n,
   8    else:
   9      print "No solution"
  10    print

Euclid's extended algorithm

Basically Euclid's algorithm for finding the largest common denominator, this one is modified in order to obtain the numbers d, x, y, where d is the dennominator and they check the following equation:
d = ax + by

   1  
   2  def euclidExtended(a, b):
   3    if b == 0:
   4      return a, 1, 0
   5    dd, xx, yy = euclidExtended(b, a % b)
   6    d, x, y = dd, yy, xx - int(a / b) * yy
   7    return d, x, y
   8  

Euclid's algorithm

Euclid(a, b) calculates the largest common denominator d, and returns it.

Uses the well-known Euclid's algorithm.

   1  
   2  def euclid(a, b):
   3    while b != 0:
   4      r = a % b
   5      a = b
   6      b = r
   7    return a

Euler's Phi function.

Returns the value of Euler's phi function for n. It basically calculates the number of relative prime integers to n smaller than n.

This only works if there the prime numbers smaller than n are stored in the array prime[] of nrPrime elements.

You can use this function to generate them:
http://snippets.dzone.com/posts/show/4189

   1  
   2  int phi(int n) {
   3    double rez = n;
   4  
   5    int i = 0;
   6    while ((i < nrPrime) && (prime[i] <= n)) {
   7      if (n % prime[i] == 0) {
   8        rez *= (double)(prime[i] - 1) / (double)prime[i];
   9      }
  10      ++i;
  11    }
  12  
  13    return rez;
  14  }


« Newer Snippets
Older Snippets »
Showing 31-40 of 50 total