Ad

Fast algorithm to test primality

import math
def isprime(num):
  if num<2 or int(num)!=num: return False
  if not num%2 and num>2: return False
  for n in range(3,math.ceil((num-1)**.5)+1,2):
    if not num%n:
      return False
  return True

Takes the square root of an int and returns a double.

double sqrt (int a,int accuracy=20) {
  double out = a;
  for(int i=0;i<accuracy;i++) {
    out = (out+a/out)/2;
  }
  return out;
}

Parses an expression.

def parse(expr): #The main parser
  ps = 0 #Number of open parentheses
  cval = 0 #Current value
  op = "+" #Current operation
  accum = "" #Accumulating value
  for i in range(len(expr)):
    c = expr[i]
    if c in ["+","-"] and not ps: #Operation not inside parens
      if op=="+": #Addition
        cval+=parse_fact(accum)
      else: #Subtraction
        cval-=parse_fact(accum)
      accum = "" #Reset the value
      op = c #New operation once that was calculated
    else:
      if c=="(": ps+=1 #Open paren
      if c==")": ps-=1 #Close paren
      accum+=c #Add a character to accumulating value
  if op=="+": #Do the operation one more time
    cval+=parse_fact(accum)
  else:
    cval-=parse_fact(accum)
  return cval
def parse_fact(term):
  ps = 0
  cval = 1
  op = "*"
  accum = ""
  for i in range(len(term)):
    c = term[i]
    if c in ["*","/"] and not ps:
      if op=="*":
        cval*=parse_val(accum)
      else:
        cval/=parse_val(accum)
      accum = ""
      op = c
    else:
      if c=="(": ps+=1
      if c==")": ps-=1
      accum+=c
  if op=="*":
    cval*=parse_val(accum)
  else:
    cval/=parse_val(accum)
  return cval
def parse_val(val):
  if val[0] == "(": #Parenthetical expression
    return parse(val[1:-1]) #Cut off parentheses and reevaluate
  else:
    return float(val) #Not parenthetical