code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
import java.math.MathContext import scala.annotation.tailrec import scala.compat.Platform.currentTime import scala.math.BigDecimal object Calculate_Pi extends App { val precision = new MathContext(32768 ) val (bigZero, bigOne, bigTwo, bigFour) = (BigDecimal(0, precision), BigDecimal(1, precision), BigDecimal(2, precision), BigDecimal(4, precision)) def bigSqrt(bd: BigDecimal) = { @tailrec def iter(x0: BigDecimal, x1: BigDecimal): BigDecimal = if (x0 == x1) x1 else iter(x1, (bd / x1 + x1) / bigTwo) iter(bigZero, BigDecimal(Math.sqrt(bd.toDouble), precision)) } @tailrec private def loop(a: BigDecimal, g: BigDecimal, sum: BigDecimal, pow: BigDecimal): BigDecimal = { if (a == g) (bigFour * (a * a)) / (bigOne - sum) else { val (_a, _g, _pow) = ((a + g) / bigTwo, bigSqrt(a * g), pow * bigTwo) loop(_a, _g, sum + ((_a * _a - (_g * _g)) * _pow), _pow) } } println(precision) val pi = loop(bigOne, bigOne / bigSqrt(bigTwo), bigZero, bigTwo) println(s"This are ${pi.toString.length - 1} digits of :") val lines = pi.toString().sliding(103, 103).mkString("\n") println(lines) println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]") }
6Arithmetic-geometric mean/Calculate Pi
16scala
kvhk
class complex { num real=0; num imag=0; complex(num r,num i){ this.real=r; this.imag=i; } complex add(complex b){ return new complex(this.real + b.real, this.imag + b.imag); } complex mult(complex b){
9Arithmetic/Complex
18dart
au1h
using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_node; using boost::spirit::node_val_data; struct parser: public boost::spirit::grammar<parser> { enum rule_ids { addsub_id, multdiv_id, value_id, real_id }; struct set_value { set_value(parser const& p): self(p) {} void operator()(tree_node<node_val_data<std::string::iterator, double> >& node, std::string::iterator begin, std::string::iterator end) const { node.value.value(self.tmp); } parser const& self; }; mutable double tmp; template<typename Scanner> struct definition { rule<Scanner, parser_tag<addsub_id> > addsub; rule<Scanner, parser_tag<multdiv_id> > multdiv; rule<Scanner, parser_tag<value_id> > value; rule<Scanner, parser_tag<real_id> > real; definition(parser const& self) { using namespace boost::spirit; addsub = multdiv >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv); multdiv = value >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value); value = real | inner_node_d[('(' >> addsub >> ')')]; real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]]; } rule<Scanner, parser_tag<addsub_id> > const& start() const { return addsub; } }; }; template<typename TreeIter> double evaluate(TreeIter const& i) { double op1, op2; switch (i->value.id().to_long()) { case parser::real_id: return i->value.value(); case parser::value_id: case parser::addsub_id: case parser::multdiv_id: op1 = evaluate(i->children.begin()); op2 = evaluate(i->children.begin()+1); switch(*i->value.begin()) { case '+': return op1 + op2; case '-': return op1 - op2; case '*': return op1 * op2; case '/': return op1 / op2; default: assert(!); } default: assert(!); } return 0; } int main() { parser eval; std::string line; while (std::cout << && std::getline(std::cin, line) && !line.empty()) { typedef boost::spirit::node_val_data_factory<double> factory_t; boost::spirit::tree_parse_info<std::string::iterator, factory_t> info = boost::spirit::ast_parse<factory_t>(line.begin(), line.end(), eval, boost::spirit::space_p); if (info.full) { std::cout << << evaluate(info.trees.begin()) << std::endl; } else { std::cout << << std::endl; } } };
11Arithmetic evaluation
5c
evav
(def precedence '{* 0, / 0 + 1, - 1}) (defn order-ops "((A x B) y C) or (A x (B y C)) depending on precedence of x and y" [[A x B y C & more]] (let [ret (if (<= (precedence x) (precedence y)) (list (list A x B) y C) (list A x (list B y C)))] (if more (recur (concat ret more)) ret))) (defn add-parens "Tree walk to add parens. All lists are length 3 afterwards." [s] (clojure.walk/postwalk #(if (seq? %) (let [c (count %)] (cond (even? c) (throw (Exception. "Must be an odd number of forms")) (= c 1) (first %) (= c 3) % (>= c 5) (order-ops %))) %) s)) (defn make-ast "Parse a string into a list of numbers, ops, and lists" [s] (-> (format "'(%s)" s) (.replaceAll , "([*+-/])" " $1 ") load-string add-parens)) (def ops {'* * '+ + '- - '/ /}) (def eval-ast (partial clojure.walk/postwalk #(if (seq? %) (let [[a o b] %] ((ops o) a b)) %))) (defn evaluate [s] "Parse and evaluate an infix arithmetic expression" (eval-ast (make-ast s))) user> (evaluate "1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5 - 22/(7 + 2*(3 - 1)) - 1)) + 1") 60
11Arithmetic evaluation
6clojure
0rsj
package main import ( "fmt" "math" ) const = 1e-14 func agm(a, g float64) float64 { for math.Abs(a-g) > math.Abs(a)* { a, g = (a+g)*.5, math.Sqrt(a*g) } return a } func main() { fmt.Println(agm(1, 1/math.Sqrt2)) }
10Arithmetic-geometric mean
0go
76r2
double agm (double a, double g) { double an = a, gn = g while ((an-gn).abs() >= 10.0**-14) { (an, gn) = [(an+gn)*0.5, (an*gn)**0.5] } an }
10Arithmetic-geometric mean
7groovy
udv9
agm :: (Floating a) => a -> a -> ((a, a) -> Bool) -> a agm a g eq = snd $ until eq step (a, g) where step (a, g) = ((a + g) / 2, sqrt (a * g)) relDiff :: (Fractional a) => (a, a) -> a relDiff (x, y) = let n = abs (x - y) d = (abs x + abs y) / 2 in n / d main :: IO () main = do let equal = (< 0.000000001) . relDiff print $ agm 1 (1 / sqrt 2) equal
10Arithmetic-geometric mean
8haskell
8j0z
public class ArithmeticGeometricMean { public static double agm(double a, double g) { double a1 = a; double g1 = g; while (Math.abs(a1 - g1) >= 1.0e-14) { double arith = (a1 + g1) / 2.0; double geom = Math.sqrt(a1 * g1); a1 = arith; g1 = geom; } return a1; } public static void main(String[] args) { System.out.println(agm(1.0, 1.0 / Math.sqrt(2.0))); } }
10Arithmetic-geometric mean
9java
eua5
function agm(a0, g0) { var an = (a0 + g0) / 2, gn = Math.sqrt(a0 * g0); while (Math.abs(an - gn) > tolerance) { an = (an + gn) / 2, gn = Math.sqrt(an * gn) } return an; } agm(1, 1 / Math.sqrt(2));
10Arithmetic-geometric mean
10javascript
07sz
int main(){ double a,b,cycles,incr,i; int steps,x=500,y=500; printf(); scanf(,&a,&b); printf(); scanf(,&cycles); printf(); scanf(,&steps); incr = 1.0/steps; initwindow(1000,1000,); for(i=0;i<=cycles*pi;i+=incr){ putpixel(x + (a + b*i)*cos(i),x + (a + b*i)*sin(i),15); } getch(); closegraph(); }
12Archimedean spiral
5c
xuwu
package main import ( "fmt" "math" "math/big" ) func main() { var recip big.Rat max := int64(1 << 19) for candidate := int64(2); candidate < max; candidate++ { sum := big.NewRat(1, candidate) max2 := int64(math.Sqrt(float64(candidate))) for factor := int64(2); factor <= max2; factor++ { if candidate%factor == 0 { sum.Add(sum, recip.SetFrac64(1, factor)) if f2 := candidate / factor; f2 != factor { sum.Add(sum, recip.SetFrac64(1, f2)) } } } if sum.Denom().Int64() == 1 { perfectstring := "" if sum.Num().Int64() == 1 { perfectstring = "perfect!" } fmt.Printf("Sum of recipr. factors of%d =%d exactly%s\n", candidate, sum.Num().Int64(), perfectstring) } } }
8Arithmetic/Rational
0go
j97d
class Rational extends Number implements Comparable { final BigInteger num, denom static final Rational ONE = new Rational(1) static final Rational ZERO = new Rational(0) Rational(BigDecimal decimal) { this( decimal.scale() < 0 ? decimal.unscaledValue() * 10 ** -decimal.scale(): decimal.unscaledValue(), decimal.scale() < 0 ? 1 : 10 ** decimal.scale() ) } Rational(BigInteger n, BigInteger d = 1) { if (!d || n == null) { n/d } (num, denom) = reduce(n, d) } private List reduce(BigInteger n, BigInteger d) { BigInteger sign = ((n < 0) ^ (d < 0)) ? -1: 1 (n, d) = [n.abs(), d.abs()] BigInteger commonFactor = gcd(n, d) [n.intdiv(commonFactor) * sign, d.intdiv(commonFactor)] } Rational toLeastTerms() { reduce(num, denom) as Rational } private BigInteger gcd(BigInteger n, BigInteger m) { n == 0 ? m: { while(m%n != 0) { (n, m) = [m%n, n] }; n }() } Rational plus(Rational r) { [num*r.denom + r.num*denom, denom*r.denom] } Rational plus(BigInteger n) { [num + n*denom, denom] } Rational plus(Number n) { this + ([n] as Rational) } Rational next() { [num + denom, denom] } Rational minus(Rational r) { [num*r.denom - r.num*denom, denom*r.denom] } Rational minus(BigInteger n) { [num - n*denom, denom] } Rational minus(Number n) { this - ([n] as Rational) } Rational previous() { [num - denom, denom] } Rational multiply(Rational r) { [num*r.num, denom*r.denom] } Rational multiply(BigInteger n) { [num*n, denom] } Rational multiply(Number n) { this * ([n] as Rational) } Rational div(Rational r) { new Rational(num*r.denom, denom*r.num) } Rational div(BigInteger n) { new Rational(num, denom*n) } Rational div(Number n) { this / ([n] as Rational) } BigInteger intdiv(BigInteger n) { num.intdiv(denom*n) } Rational negative() { [-num, denom] } Rational abs() { [num.abs(), denom] } Rational reciprocal() { new Rational(denom, num) } Rational power(BigInteger n) { def (nu, de) = (n < 0 ? [denom, num]: [num, denom])*.power(n.abs()) new Rational (nu, de) } boolean asBoolean() { num != 0 } BigDecimal toBigDecimal() { (num as BigDecimal)/(denom as BigDecimal) } BigInteger toBigInteger() { num.intdiv(denom) } Double toDouble() { toBigDecimal().toDouble() } double doubleValue() { toDouble() as double } Float toFloat() { toBigDecimal().toFloat() } float floatValue() { toFloat() as float } Integer toInteger() { toBigInteger().toInteger() } int intValue() { toInteger() as int } Long toLong() { toBigInteger().toLong() } long longValue() { toLong() as long } Object asType(Class type) { switch (type) { case this.class: return this case [Boolean, Boolean.TYPE]: return asBoolean() case BigDecimal: return toBigDecimal() case BigInteger: return toBigInteger() case [Double, Double.TYPE]: return toDouble() case [Float, Float.TYPE]: return toFloat() case [Integer, Integer.TYPE]: return toInteger() case [Long, Long.TYPE]: return toLong() case String: return toString() default: throw new ClassCastException("Cannot convert from type Rational to type " + type) } } boolean equals(o) { compareTo(o) == 0 } int compareTo(o) { o instanceof Rational ? compareTo(o as Rational) : o instanceof Number ? compareTo(o as Number) : (Double.NaN as int) } int compareTo(Rational r) { num*r.denom <=> denom*r.num } int compareTo(Number n) { num <=> denom*(n as BigInteger) } int hashCode() { [num, denom].hashCode() } String toString() { "${num}
8Arithmetic/Rational
7groovy
5zuv
null
10Arithmetic-geometric mean
11kotlin
k9h3
import Data.Ratio ((%)) main = do let n = 4 mapM_ print $ take n [ candidate | candidate <- [2 .. 2 ^ 19] , getSum candidate == 1 ] where getSum candidate = 1 % candidate + sum [ 1 % factor + 1 % (candidate `div` factor) | factor <- [2 .. floor (sqrt (fromIntegral candidate))] , candidate `mod` factor == 0 ]
8Arithmetic/Rational
8haskell
ob8p
(use '(incanter core stats charts io)) (defn Arquimidean-function [a b theta] (+ a (* theta b))) (defn transform-pl-xy [r theta] (let [x (* r (sin theta)) y (* r (cos theta))] [x y])) (defn arq-spiral [t] (transform-pl-xy (Arquimidean-function 0 7 t) t)) (view (parametric-plot arq-spiral 0 (* 10 Math/PI)))
12Archimedean spiral
6clojure
o78j
int myArray2[10] = { 1, 2, 0 }; float myFloats[] ={1.2, 2.5, 3.333, 4.92, 11.2, 22.0 };
13Arrays
5c
ye6f
package main import ( "image" "image/color" "image/draw" "image/png" "log" "math" "os" ) func main() { const ( width, height = 600, 600 centre = width / 2.0 degreesIncr = 0.1 * math.Pi / 180 turns = 2 stop = 360 * turns * 10 * degreesIncr fileName = "spiral.png" ) img := image.NewNRGBA(image.Rect(0, 0, width, height))
12Archimedean spiral
0go
l0cw
function agm(a, b, tolerance) if not tolerance or tolerance < 1e-15 then tolerance = 1e-15 end repeat a, b = (a + b) / 2, math.sqrt(a * b) until math.abs(a-b) < tolerance return a end print(string.format("%.15f", agm(1, 1 / math.sqrt(2))))
10Arithmetic-geometric mean
1lua
bcka
#!/usr/bin/env stack import Codec.Picture( PixelRGBA8( .. ), writePng ) import Graphics.Rasterific import Graphics.Rasterific.Texture import Graphics.Rasterific.Transformations archimedeanPoint a b t = V2 x y where r = a + b * t x = r * cos t y = r * sin t main :: IO () main = do let white = PixelRGBA8 255 255 255 255 drawColor = PixelRGBA8 0xFF 0x53 0x73 255 size = 800 points = map (archimedeanPoint 0 10) [0, 0.01 .. 60] hSize = fromIntegral size / 2 img = renderDrawing size size white $ withTransformation (translate $ V2 hSize hSize) $ withTexture (uniformTexture drawColor) $ stroke 4 JoinRound (CapRound, CapRound) $ polyline points writePng "SpiralHaskell.png" img
12Archimedean spiral
8haskell
1cps
public class BigRationalFindPerfectNumbers { public static void main(String[] args) { int MAX_NUM = 1 << 19; System.out.println("Searching for perfect numbers in the range [1, " + (MAX_NUM - 1) + "]"); BigRational TWO = BigRational.valueOf(2); for (int i = 1; i < MAX_NUM; i++) { BigRational reciprocalSum = BigRational.ONE; if (i > 1) reciprocalSum = reciprocalSum.add(BigRational.valueOf(i).reciprocal()); int maxDivisor = (int) Math.sqrt(i); if (maxDivisor >= i) maxDivisor--; for (int divisor = 2; divisor <= maxDivisor; divisor++) { if (i % divisor == 0) { reciprocalSum = reciprocalSum.add(BigRational.valueOf(divisor).reciprocal()); int dividend = i / divisor; if (divisor != dividend) reciprocalSum = reciprocalSum.add(BigRational.valueOf(dividend).reciprocal()); } } if (reciprocalSum.equals(TWO)) System.out.println(String.valueOf(i) + " is a perfect number"); } } }
8Arithmetic/Rational
9java
wgej
import java.awt.*; import static java.lang.Math.*; import javax.swing.*; public class ArchimedeanSpiral extends JPanel { public ArchimedeanSpiral() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } void drawGrid(Graphics2D g) { g.setColor(new Color(0xEEEEEE)); g.setStroke(new BasicStroke(2)); double angle = toRadians(45); int w = getWidth(); int center = w / 2; int margin = 10; int numRings = 8; int spacing = (w - 2 * margin) / (numRings * 2); for (int i = 0; i < numRings; i++) { int pos = margin + i * spacing; int size = w - (2 * margin + i * 2 * spacing); g.drawOval(pos, pos, size, size); double ia = i * angle; int x2 = center + (int) (cos(ia) * (w - 2 * margin) / 2); int y2 = center - (int) (sin(ia) * (w - 2 * margin) / 2); g.drawLine(center, center, x2, y2); } } void drawSpiral(Graphics2D g) { g.setStroke(new BasicStroke(2)); g.setColor(Color.orange); double degrees = toRadians(0.1); double center = getWidth() / 2; double end = 360 * 2 * 10 * degrees; double a = 0; double b = 20; double c = 1; for (double theta = 0; theta < end; theta += degrees) { double r = a + b * pow(theta, 1 / c); double x = r * cos(theta); double y = r * sin(theta); plot(g, (int) (center + x), (int) (center - y)); } } void plot(Graphics2D g, int x, int y) { g.drawOval(x, y, 1, 1); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawGrid(g); drawSpiral(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Archimedean Spiral"); f.setResizable(false); f.add(new ArchimedeanSpiral(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
12Archimedean spiral
9java
7zrj
package main import ( "fmt" "math/cmplx" ) func main() { a := 1 + 1i b := 3.14159 + 1.25i fmt.Println("a: ", a) fmt.Println("b: ", b) fmt.Println("a + b: ", a+b) fmt.Println("a * b: ", a*b) fmt.Println("-a: ", -a) fmt.Println("1 / a: ", 1/a) fmt.Println("a: ", cmplx.Conj(a)) }
9Arithmetic/Complex
0go
ufvt
null
8Arithmetic/Rational
10javascript
8k0l
enum Op { ADD('+', 2), SUBTRACT('-', 2), MULTIPLY('*', 1), DIVIDE('/', 1); static { ADD.operation = { a, b -> a + b } SUBTRACT.operation = { a, b -> a - b } MULTIPLY.operation = { a, b -> a * b } DIVIDE.operation = { a, b -> a / b } } final String symbol final int precedence Closure operation private Op(String symbol, int precedence) { this.symbol = symbol this.precedence = precedence } String toString() { symbol } static Op fromSymbol(String symbol) { Op.values().find { it.symbol == symbol } } } interface Expression { Number evaluate(); } class Constant implements Expression { Number value Constant (Number value) { this.value = value } Constant (String str) { try { this.value = str as BigInteger } catch (e) { this.value = str as BigDecimal } } Number evaluate() { value } String toString() { "${value}" } } class Term implements Expression { Op op Expression left, right Number evaluate() { op.operation(left.evaluate(), right.evaluate()) } String toString() { "(${op} ${left} ${right})" } } void fail(String msg, Closure cond = {true}) { if (cond()) throw new IllegalArgumentException("Cannot parse expression: ${msg}") } Expression parse(String expr) { def tokens = tokenize(expr) def elements = groupByParens(tokens, 0) parse(elements) } List tokenize(String expr) { def tokens = [] def constStr = "" def captureConstant = { i -> if (constStr) { try { tokens << new Constant(constStr) } catch (NumberFormatException e) { fail "Invalid constant '${constStr}' near position ${i}" } constStr = '' } } for(def i = 0; i<expr.size(); i++) { def c = expr[i] def constSign = c in ['+','-'] && constStr.empty && (tokens.empty || tokens[-1] != ')') def isConstChar = { it in ['.'] + ('0'..'9') || constSign } if (c in ([')'] + Op.values()*.symbol) && !constSign) { captureConstant(i) } switch (c) { case ~/\s/: break case isConstChar: constStr += c; break case Op.values()*.symbol: tokens << Op.fromSymbol(c); break case ['(',')']: tokens << c; break default: fail "Invalid character '${c}' at position ${i+1}" } } captureConstant(expr.size()) tokens } List groupByParens(List tokens, int depth) { def deepness = depth def tokenGroups = [] for (def i = 0; i < tokens.size(); i++) { def token = tokens[i] switch (token) { case '(': fail("'(' too close to end of expression") { i+2 > tokens.size() } def subGroup = groupByParens(tokens[i+1..-1], depth+1) tokenGroups << subGroup[0..-2] i += subGroup[-1] + 1 break case ')': fail("Unbalanced parens, found extra ')'") { deepness == 0 } tokenGroups << i return tokenGroups default: tokenGroups << token } } fail("Unbalanced parens, unclosed groupings at end of expression") { deepness != 0 } def n = tokenGroups.size() fail("The operand/operator sequence is wrong") { n%2 == 0 } (0..<n).each { def i = it fail("The operand/operator sequence is wrong") { (i%2 == 0) == (tokenGroups[i] instanceof Op) } } tokenGroups } Expression parse(List elements) { while (elements.size() > 1) { def n = elements.size() fail ("The operand/operator sequence is wrong") { n%2 == 0 } def groupLoc = (0..<n).find { i -> elements[i] instanceof List } if (groupLoc != null) { elements[groupLoc] = parse(elements[groupLoc]) continue } def opLoc = (0..<n).find { i -> elements[i] instanceof Op && elements[i].precedence == 1 } \ ?: (0..<n).find { i -> elements[i] instanceof Op && elements[i].precedence == 2 } if (opLoc != null) { fail ("Operator out of sequence") { opLoc%2 == 0 } def term = new Term(left:elements[opLoc-1], op:elements[opLoc], right:elements[opLoc+1]) elements[(opLoc-1)..(opLoc+1)] = [term] continue } } return elements[0] instanceof List ? parse(elements[0]): elements[0] }
11Arithmetic evaluation
0go
9smt
<!-- ArchiSpiral.html --> <html> <head><title>Archimedean spiral</title></head> <body onload="pAS(35,'navy');"> <h3>Archimedean spiral</h3> <p id=bo></p> <canvas id="canvId" width="640" height="640" style="border: 2px outset;"></canvas> <script>
12Archimedean spiral
10javascript
p9b7
class Complex { final Number real, imag static final Complex i = [0,1] as Complex Complex(Number r, Number i = 0) { (real, imag) = [r, i] } Complex(Map that) { (real, imag) = [that.real ?: 0, that.imag ?: 0] } Complex plus (Complex c) { [real + c.real, imag + c.imag] as Complex } Complex plus (Number n) { [real + n, imag] as Complex } Complex minus (Complex c) { [real - c.real, imag - c.imag] as Complex } Complex minus (Number n) { [real - n, imag] as Complex } Complex multiply (Complex c) { [real*c.real - imag*c.imag , imag*c.real + real*c.imag] as Complex } Complex multiply (Number n) { [real*n , imag*n] as Complex } Complex div (Complex c) { this * c.recip() } Complex div (Number n) { this * (1/n) } Complex negative () { [-real, -imag] as Complex } Complex bitwiseNegate () { [real, -imag] as Complex }
9Arithmetic/Complex
7groovy
98m4
enum Op { ADD('+', 2), SUBTRACT('-', 2), MULTIPLY('*', 1), DIVIDE('/', 1); static { ADD.operation = { a, b -> a + b } SUBTRACT.operation = { a, b -> a - b } MULTIPLY.operation = { a, b -> a * b } DIVIDE.operation = { a, b -> a / b } } final String symbol final int precedence Closure operation private Op(String symbol, int precedence) { this.symbol = symbol this.precedence = precedence } String toString() { symbol } static Op fromSymbol(String symbol) { Op.values().find { it.symbol == symbol } } } interface Expression { Number evaluate(); } class Constant implements Expression { Number value Constant (Number value) { this.value = value } Constant (String str) { try { this.value = str as BigInteger } catch (e) { this.value = str as BigDecimal } } Number evaluate() { value } String toString() { "${value}" } } class Term implements Expression { Op op Expression left, right Number evaluate() { op.operation(left.evaluate(), right.evaluate()) } String toString() { "(${op} ${left} ${right})" } } void fail(String msg, Closure cond = {true}) { if (cond()) throw new IllegalArgumentException("Cannot parse expression: ${msg}") } Expression parse(String expr) { def tokens = tokenize(expr) def elements = groupByParens(tokens, 0) parse(elements) } List tokenize(String expr) { def tokens = [] def constStr = "" def captureConstant = { i -> if (constStr) { try { tokens << new Constant(constStr) } catch (NumberFormatException e) { fail "Invalid constant '${constStr}' near position ${i}" } constStr = '' } } for(def i = 0; i<expr.size(); i++) { def c = expr[i] def constSign = c in ['+','-'] && constStr.empty && (tokens.empty || tokens[-1] != ')') def isConstChar = { it in ['.'] + ('0'..'9') || constSign } if (c in ([')'] + Op.values()*.symbol) && !constSign) { captureConstant(i) } switch (c) { case ~/\s/: break case isConstChar: constStr += c; break case Op.values()*.symbol: tokens << Op.fromSymbol(c); break case ['(',')']: tokens << c; break default: fail "Invalid character '${c}' at position ${i+1}" } } captureConstant(expr.size()) tokens } List groupByParens(List tokens, int depth) { def deepness = depth def tokenGroups = [] for (def i = 0; i < tokens.size(); i++) { def token = tokens[i] switch (token) { case '(': fail("'(' too close to end of expression") { i+2 > tokens.size() } def subGroup = groupByParens(tokens[i+1..-1], depth+1) tokenGroups << subGroup[0..-2] i += subGroup[-1] + 1 break case ')': fail("Unbalanced parens, found extra ')'") { deepness == 0 } tokenGroups << i return tokenGroups default: tokenGroups << token } } fail("Unbalanced parens, unclosed groupings at end of expression") { deepness != 0 } def n = tokenGroups.size() fail("The operand/operator sequence is wrong") { n%2 == 0 } (0..<n).each { def i = it fail("The operand/operator sequence is wrong") { (i%2 == 0) == (tokenGroups[i] instanceof Op) } } tokenGroups } Expression parse(List elements) { while (elements.size() > 1) { def n = elements.size() fail ("The operand/operator sequence is wrong") { n%2 == 0 } def groupLoc = (0..<n).find { i -> elements[i] instanceof List } if (groupLoc != null) { elements[groupLoc] = parse(elements[groupLoc]) continue } def opLoc = (0..<n).find { i -> elements[i] instanceof Op && elements[i].precedence == 1 } \ ?: (0..<n).find { i -> elements[i] instanceof Op && elements[i].precedence == 2 } if (opLoc != null) { fail ("Operator out of sequence") { opLoc%2 == 0 } def term = new Term(left:elements[opLoc-1], op:elements[opLoc], right:elements[opLoc+1]) elements[(opLoc-1)..(opLoc+1)] = [term] continue } } return elements[0] instanceof List ? parse(elements[0]): elements[0] }
11Arithmetic evaluation
7groovy
zat5
null
12Archimedean spiral
11kotlin
uivc
import Data.Complex main = do let a = 1.0:+ 2.0 let b = 4 putStrLn $ "Add: " ++ show (a + b) putStrLn $ "Subtract: " ++ show (a - b) putStrLn $ "Multiply: " ++ show (a * b) putStrLn $ "Divide: " ++ show (a / b) putStrLn $ "Negate: " ++ show (-a) putStrLn $ "Inverse: " ++ show (recip a) putStrLn $ "Conjugate:" ++ show (conjugate a)
9Arithmetic/Complex
8haskell
w4ed
import Text.Parsec import Text.Parsec.Expr import Text.Parsec.Combinator import Data.Functor import Data.Function (on) data Exp = Num Int | Add Exp Exp | Sub Exp Exp | Mul Exp Exp | Div Exp Exp expr :: Stream s m Char => ParsecT s u m Exp expr = buildExpressionParser table factor where table = [ [op "*" Mul AssocLeft, op "/" Div AssocLeft] , [op "+" Add AssocLeft, op "-" Sub AssocLeft] ] op s f = Infix (f <$ string s) factor = (between `on` char) '(' ')' expr <|> (Num . read <$> many1 digit) eval :: Integral a => Exp -> a eval (Num x) = fromIntegral x eval (Add a b) = eval a + eval b eval (Sub a b) = eval a - eval b eval (Mul a b) = eval a * eval b eval (Div a b) = eval a `div` eval b solution :: Integral a => String -> a solution = either (const (error "Did not parse")) eval . parse expr "" main :: IO () main = print $ solution "(1+3)*7"
11Arithmetic evaluation
8haskell
b9k2
a=1 b=2 cycles=40 step=0.001 x=0 y=0 function love.load() x = love.graphics.getWidth()/2 y = love.graphics.getHeight()/2 end function love.draw() love.graphics.print("a="..a,16,16) love.graphics.print("b="..b,16,32) for i=0,cycles*math.pi,step do love.graphics.points(x+(a + b*i)*math.cos(i),y+(a + b*i)*math.sin(i)) end end
12Archimedean spiral
1lua
5nu6
null
8Arithmetic/Rational
11kotlin
b2kb
user=> (def my-list (list 1 2 3 4 5)) user=> my-list (1 2 3 4 5) user=> (first my-list) 1 user=> (nth my-list 3) 4 user=> (conj my-list 100) (100 1 2 3 4 5) user=> my-list (1 2 3 4 5) user=> (def my-new-list (conj my-list 100)) user=> my-new-list (100 1 2 3 4 5) user=> (cons 200 my-new-list) (200 100 1 2 3 4 5) user=> (def my-vec [1 2 3 4 5 6]) user=> (conj my-vec 300) [1 2 3 4 5 6 300]
13Arrays
6clojure
20l1
import java.util.Stack; public class ArithmeticEvaluation { public interface Expression { BigRational eval(); } public enum Parentheses {LEFT} public enum BinaryOperator { ADD('+', 1), SUB('-', 1), MUL('*', 2), DIV('/', 2); public final char symbol; public final int precedence; BinaryOperator(char symbol, int precedence) { this.symbol = symbol; this.precedence = precedence; } public BigRational eval(BigRational leftValue, BigRational rightValue) { switch (this) { case ADD: return leftValue.add(rightValue); case SUB: return leftValue.subtract(rightValue); case MUL: return leftValue.multiply(rightValue); case DIV: return leftValue.divide(rightValue); } throw new IllegalStateException(); } public static BinaryOperator forSymbol(char symbol) { for (BinaryOperator operator : values()) { if (operator.symbol == symbol) { return operator; } } throw new IllegalArgumentException(String.valueOf(symbol)); } } public static class Number implements Expression { private final BigRational number; public Number(BigRational number) { this.number = number; } @Override public BigRational eval() { return number; } @Override public String toString() { return number.toString(); } } public static class BinaryExpression implements Expression { public final Expression leftOperand; public final BinaryOperator operator; public final Expression rightOperand; public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) { this.leftOperand = leftOperand; this.operator = operator; this.rightOperand = rightOperand; } @Override public BigRational eval() { BigRational leftValue = leftOperand.eval(); BigRational rightValue = rightOperand.eval(); return operator.eval(leftValue, rightValue); } @Override public String toString() { return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")"; } } private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) { Expression rightOperand = operands.pop(); Expression leftOperand = operands.pop(); operands.push(new BinaryExpression(leftOperand, operator, rightOperand)); } public static Expression parse(String input) { int curIndex = 0; boolean afterOperand = false; Stack<Expression> operands = new Stack<>(); Stack<Object> operators = new Stack<>(); while (curIndex < input.length()) { int startIndex = curIndex; char c = input.charAt(curIndex++); if (Character.isWhitespace(c)) continue; if (afterOperand) { if (c == ')') { Object operator; while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT)) createNewOperand((BinaryOperator) operator, operands); continue; } afterOperand = false; BinaryOperator operator = BinaryOperator.forSymbol(c); while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence)) createNewOperand((BinaryOperator) operators.pop(), operands); operators.push(operator); continue; } if (c == '(') { operators.push(Parentheses.LEFT); continue; } afterOperand = true; while (curIndex < input.length()) { c = input.charAt(curIndex); if (((c < '0') || (c > '9')) && (c != '.')) break; curIndex++; } operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex)))); } while (!operators.isEmpty()) { Object operator = operators.pop(); if (operator == Parentheses.LEFT) throw new IllegalArgumentException(); createNewOperand((BinaryOperator) operator, operands); } Expression expression = operands.pop(); if (!operands.isEmpty()) throw new IllegalArgumentException(); return expression; } public static void main(String[] args) { String[] testExpressions = { "2+3", "2+3/4", "2*3-4", "2*(3+4)+5/6", "2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10", "2*-3--4+-.25"}; for (String testExpression : testExpressions) { Expression expression = parse(testExpression); System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval()); } } }
11Arithmetic evaluation
9java
gt4m
use Imager; use constant PI => 3.14159265; my ($w, $h) = (400, 400); my $img = Imager->new(xsize => $w, ysize => $h); for ($theta = 0; $theta < 52*PI; $theta += 0.025) { $x = $w/2 + $theta * cos($theta/PI); $y = $h/2 + $theta * sin($theta/PI); $img->setpixel(x => $x, y => $y, color => ' } $img->write(file => 'Archimedean-spiral.png');
12Archimedean spiral
2perl
8r0w
public class Complex { public final double real; public final double imag; public Complex() { this(0, 0); } public Complex(double r, double i) { real = r; imag = i; } public Complex add(Complex b) { return new Complex(this.real + b.real, this.imag + b.imag); } public Complex mult(Complex b) {
9Arithmetic/Complex
9java
kchm
function gcd(a,b) return a == 0 and b or gcd(b % a, a) end do local function coerce(a, b) if type(a) == "number" then return rational(a, 1), b end if type(b) == "number" then return a, rational(b, 1) end return a, b end rational = setmetatable({ __add = function(a, b) local a, b = coerce(a, b) return rational(a.num * b.den + a.den * b.num, a.den * b.den) end, __sub = function(a, b) local a, b = coerce(a, b) return rational(a.num * b.den - a.den * b.num, a.den * b.den) end, __mul = function(a, b) local a, b = coerce(a, b) return rational(a.num * b.num, a.den * b.den) end, __div = function(a, b) local a, b = coerce(a, b) return rational(a.num * b.den, a.den * b.num) end, __pow = function(a, b) if type(a) == "number" then return a ^ (b.num / b.den) end return rational(a.num ^ b, a.den ^ b)
8Arithmetic/Rational
1lua
pvbw
function evalArithmeticExp(s) { s = s.replace(/\s/g,'').replace(/^\+/,''); var rePara = /\([^\(\)]*\)/; var exp = s.match(rePara); while (exp = s.match(rePara)) { s = s.replace(exp[0], evalExp(exp[0])); } return evalExp(s); function evalExp(s) { s = s.replace(/[\(\)]/g,''); var reMD = /\d+\.?\d*\s*[\*\/]\s*[+-]?\d+\.?\d*/; var reM = /\*/; var reAS = /-?\d+\.?\d*\s*[\+-]\s*[+-]?\d+\.?\d*/; var reA = /\d\+/; var exp; while (exp = s.match(reMD)) { s = exp[0].match(reM)? s.replace(exp[0], multiply(exp[0])) : s.replace(exp[0], divide(exp[0])); } while (exp = s.match(reAS)) { s = exp[0].match(reA)? s.replace(exp[0], add(exp[0])) : s.replace(exp[0], subtract(exp[0])); } return '' + s; function multiply(s, b) { b = s.split('*'); return b[0] * b[1]; } function divide(s, b) { b = s.split('/'); return b[0] / b[1]; } function add(s, b) { s = s.replace(/^\+/,'').replace(/\++/,'+'); b = s.split('+'); return Number(b[0]) + Number(b[1]); } function subtract(s, b) { s = s.replace(/\+-|-\+/g,'-'); if (s.match(/--/)) { return add(s.replace(/--/,'+')); } b = s.split('-'); return b.length == 3? -1 * b[1] - b[2] : b[0] - b[1]; } } }
11Arithmetic evaluation
10javascript
kmhq
function Complex(r, i) { this.r = r; this.i = i; } Complex.add = function() { var num = arguments[0]; for(var i = 1, ilim = arguments.length; i < ilim; i += 1){ num.r += arguments[i].r; num.i += arguments[i].i; } return num; } Complex.multiply = function() { var num = arguments[0]; for(var i = 1, ilim = arguments.length; i < ilim; i += 1){ num.r = (num.r * arguments[i].r) - (num.i * arguments[i].i); num.i = (num.i * arguments[i].r) - (num.r * arguments[i].i); } return num; } Complex.negate = function (z) { return new Complex(-1*z.r, -1*z.i); } Complex.invert = function(z) { var denom = Math.pow(z.r,2) + Math.pow(z.i,2); return new Complex(z.r/denom, -1*z.i/denom); } Complex.conjugate = function(z) { return new Complex(z.r, -1*z.i); }
9Arithmetic/Complex
10javascript
e5ao
from turtle import * from math import * color() down() for i in range(200): t = i / 20 * pi x = (1 + 5 * t) * cos(t) y = (1 + 5 * t) * sin(t) goto(x, y) up() done()
12Archimedean spiral
3python
o781
with(list(s=seq(0, 10 * pi, length.out=500)), plot((1 + s) * exp(1i * s), type="l"))
12Archimedean spiral
13r
q5xs
null
11Arithmetic evaluation
11kotlin
2oli
class Complex(private val real: Double, private val imag: Double) { operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag) operator fun times(other: Complex) = Complex( real * other.real - imag * other.imag, real * other.imag + imag * other.real ) fun inv(): Complex { val denom = real * real + imag * imag return Complex(real / denom, -imag / denom) } operator fun unaryMinus() = Complex(-real, -imag) operator fun minus(other: Complex) = this + (-other) operator fun div(other: Complex) = this * other.inv() fun conj() = Complex(real, -imag) override fun toString() = if (imag >= 0.0) "$real + ${imag}i" else "$real - ${-imag}i" } fun main(args: Array<String>) { val x = Complex(1.0, 3.0) val y = Complex(5.0, 2.0) println("x = $x") println("y = $y") println("x + y = ${x + y}") println("x - y = ${x - y}") println("x * y = ${x * y}") println("x / y = ${x / y}") println("-x = ${-x}") println("1 / x = ${x.inv()}") println("x* = ${x.conj()}") }
9Arithmetic/Complex
11kotlin
g34d
my ($a0, $g0, $a1, $g1); sub agm($$) { $a0 = shift; $g0 = shift; do { $a1 = ($a0 + $g0)/2; $g1 = sqrt($a0 * $g0); $a0 = ($a1 + $g1)/2; $g0 = sqrt($a1 * $g1); } while ($a0 != $a1); return $a0; } print agm(1, 1/sqrt(2))."\n";
10Arithmetic-geometric mean
2perl
3wzs
INCR = 0.1 attr_reader :x, :theta def setup sketch_title 'Archimedian Spiral' @theta = 0 @x = 0 background(255) translate(width / 2.0, height / 2.0) begin_shape (0..50*PI).step(INCR) do |theta| @x = theta * cos(theta / PI) curve_vertex(x, theta * sin(theta / PI)) end end_shape end def settings size(300, 300) end
12Archimedean spiral
14ruby
nhit
require"lpeg" P, R, C, S, V = lpeg.P, lpeg.R, lpeg.C, lpeg.S, lpeg.V
11Arithmetic evaluation
1lua
vi2x
#[macro_use(px)] extern crate bmp; use bmp::{Image, Pixel}; use std::f64; fn main() { let width = 600u32; let half_width = (width / 2) as i32; let mut img = Image::new(width, width); let draw_color = px!(255, 128, 128);
12Archimedean spiral
15rust
dkny
define('PRECISION', 13); function agm($a0, $g0, $tolerance = 1e-10) { $limit = number_format($tolerance, PRECISION, '.', ''); $an = $a0; $gn = $g0; do { list($an, $gn) = array( bcdiv(bcadd($an, $gn), 2), bcsqrt(bcmul($an, $gn)), ); } while (bccomp(bcsub($an, $gn), $limit) > 0); return $an; } bcscale(PRECISION); echo agm(1, 1 / bcsqrt(2));
10Arithmetic-geometric mean
12php
plba
int main() { printf(, pow(0,0)); double complex c = cpow(0,0); printf(, creal(c), cimag(c)); return 0; }
14Zero to the zero power
5c
v02o
object ArchimedeanSpiral extends App { SwingUtilities.invokeLater(() => new JFrame("Archimedean Spiral") { class ArchimedeanSpiral extends JPanel { setPreferredSize(new Dimension(640, 640)) setBackground(Color.white) private def drawGrid(g: Graphics2D): Unit = { val (angle, margin, numRings) = (toRadians(45), 10, 8) val w = getWidth val (center, spacing) = (w / 2, (w - 2 * margin) / (numRings * 2)) g.setColor(new Color(0xEEEEEE)) for (i <- 0 until numRings) { val pos = margin + i * spacing val size = w - (2 * margin + i * 2 * spacing) g.drawOval(pos, pos, size, size) val ia = i * angle val x2 = center + (cos(ia) * (w - 2 * margin) / 2).toInt val y2 = center - (sin(ia) * (w - 2 * margin) / 2).toInt g.drawLine(center, center, x2, y2) } } private def drawSpiral(g: Graphics2D): Unit = { val (degrees: Double, center) = (toRadians(0.1), getWidth / 2) val (a, b, c, end) = (0, 20, 1, 360 * 2 * 10 * degrees) def plot(g: Graphics2D, x: Int, y: Int): Unit = g.drawOval(x, y, 1, 1) def iter(theta: Double): Double = { if (theta < end) { val r = a + b * pow(theta, 1 / c) val x = r * cos(theta) val y = r * sin(theta) plot(g, (center + x).toInt, (center - y).toInt) iter(theta + degrees) } else theta } g.setStroke(new BasicStroke(2)) g.setColor(Color.orange) iter(0) } override def paintComponent(gg: Graphics): Unit = { super.paintComponent(gg) val g = gg.asInstanceOf[Graphics2D] g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawGrid(g) drawSpiral(g) } } add(new ArchimedeanSpiral, BorderLayout.CENTER) pack() setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) setLocationRelativeTo(null) setResizable(false) setVisible(true) } ) }
12Archimedean spiral
16scala
z1tr
null
9Arithmetic/Complex
1lua
r6ga
main(){
13Arrays
18dart
dhnj
user=> (use 'clojure.math.numeric-tower) user=> (expt 0 0) 1 user=> (Math/pow 0 0) 1.0
14Zero to the zero power
6clojure
rdg2
<Rows> <Columns> <Blank pixel character> <Image Pixel character> <Image of specified rows and columns made up of the two pixel types specified in the second line.>
15Zhang-Suen thinning algorithm
5c
u0v4
typedef unsigned long long u64; u64 fib[] = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073ULL, 4807526976ULL, 7778742049ULL, 12586269025ULL, 20365011074ULL, 32951280099ULL, 53316291173ULL, 86267571272ULL, 139583862445ULL, 225851433717ULL, 365435296162ULL, 591286729879ULL, 956722026041ULL, 1548008755920ULL, 2504730781961ULL, 4052739537881ULL, 6557470319842ULL, 10610209857723ULL, 17167680177565ULL, 27777890035288ULL }; u64 fibbinary(u64 n) { if (n >= fib[64]) return FIB_INVALID; u64 ret = 0; int i; for (i = 64; i--; ) if (n >= fib[i]) { ret |= 1ULL << i; n -= fib[i]; } return ret; } void bprint(u64 n, int width) { if (width > 64) width = 64; u64 b; for (b = 1ULL << (width - 1); b; b >>= 1) putchar(b == 1 && !n ? '0' : b > n ? ' ' : b & n ? '1' : '0'); putchar('\n'); } int main(void) { int i; for (i = 0; i <= 20; i++) printf(, i), bprint(fibbinary(i), 8); return 0; }
16Zeckendorf number representation
5c
go45
from math import sqrt def agm(a0, g0, tolerance=1e-10): an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0) while abs(an - gn) > tolerance: an, gn = (an + gn) / 2.0, sqrt(an * gn) return an print agm(1, 1 / sqrt(2))
10Arithmetic-geometric mean
3python
6x3w
arithmeticMean <- function(a, b) { (a + b)/2 } geometricMean <- function(a, b) { sqrt(a * b) } arithmeticGeometricMean <- function(a, b) { rel_error <- abs(a - b) / pmax(a, b) if (all(rel_error < .Machine$double.eps, na.rm=TRUE)) { agm <- a return(data.frame(agm, rel_error)); } Recall(arithmeticMean(a, b), geometricMean(a, b)) } agm <- arithmeticGeometricMean(1, 1/sqrt(2)) print(format(agm, digits=16))
10Arithmetic-geometric mean
13r
f1dc
int inv(int a) { return a ^ -1; } struct Zeckendorf { int dVal, dLen; }; void a(struct Zeckendorf *self, int n) { void b(struct Zeckendorf *, int); int i = n; while (true) { if (self->dLen < i) self->dLen = i; int j = (self->dVal >> (i * 2)) & 3; switch (j) { case 0: case 1: return; case 2: if (((self->dVal >> ((i + 1) * 2)) & 1) != 1) return; self->dVal += 1 << (i * 2 + 1); return; case 3: self->dVal = self->dVal & inv(3 << (i * 2)); b(self, (i + 1) * 2); break; default: break; } i++; } } void b(struct Zeckendorf *self, int pos) { void increment(struct Zeckendorf *); if (pos == 0) { increment(self); return; } if (((self->dVal >> pos) & 1) == 0) { self->dVal += 1 << pos; a(self, pos / 2); if (pos > 1) a(self, pos / 2 - 1); } else { self->dVal = self->dVal & inv(1 << pos); b(self, pos + 1); b(self, pos - (pos > 1 ? 2 : 1)); } } void c(struct Zeckendorf *self, int pos) { if (((self->dVal >> pos) & 1) == 1) { self->dVal = self->dVal & inv(1 << pos); return; } c(self, pos + 1); if (pos > 0) { b(self, pos - 1); } else { increment(self); } } struct Zeckendorf makeZeckendorf(char *x) { struct Zeckendorf z = { 0, 0 }; int i = strlen(x) - 1; int q = 1; z.dLen = i / 2; while (i >= 0) { z.dVal += (x[i] - '0') * q; q *= 2; i--; } return z; } void increment(struct Zeckendorf *self) { self->dVal++; a(self, 0); } void addAssign(struct Zeckendorf *self, struct Zeckendorf rhs) { int gn; for (gn = 0; gn < (rhs.dLen + 1) * 2; gn++) { if (((rhs.dVal >> gn) & 1) == 1) { b(self, gn); } } } void subAssign(struct Zeckendorf *self, struct Zeckendorf rhs) { int gn; for (gn = 0; gn < (rhs.dLen + 1) * 2; gn++) { if (((rhs.dVal >> gn) & 1) == 1) { c(self, gn); } } while ((((self->dVal >> self->dLen * 2) & 3) == 0) || (self->dLen == 0)) { self->dLen--; } } void mulAssign(struct Zeckendorf *self, struct Zeckendorf rhs) { struct Zeckendorf na = rhs; struct Zeckendorf nb = rhs; struct Zeckendorf nr = makeZeckendorf(); struct Zeckendorf nt; int i; for (i = 0; i < (self->dLen + 1) * 2; i++) { if (((self->dVal >> i) & 1) > 0) addAssign(&nr, nb); nt = nb; addAssign(&nb, na); na = nt; } *self = nr; } void printZeckendorf(struct Zeckendorf z) { static const char *const dig[3] = { , , }; static const char *const dig1[3] = { , , }; if (z.dVal == 0) { printf(); return; } else { int idx = (z.dVal >> (z.dLen * 2)) & 3; int i; printf(dig1[idx]); for (i = z.dLen - 1; i >= 0; i--) { idx = (z.dVal >> (i * 2)) & 3; printf(dig[idx]); } } } int main() { struct Zeckendorf g; printf(); g = makeZeckendorf(); addAssign(&g, makeZeckendorf()); printZeckendorf(g); printf(); addAssign(&g, makeZeckendorf()); printZeckendorf(g); printf(); addAssign(&g, makeZeckendorf()); printZeckendorf(g); printf(); addAssign(&g, makeZeckendorf()); printZeckendorf(g); printf(); addAssign(&g, makeZeckendorf()); printZeckendorf(g); printf(); printf(); g = makeZeckendorf(); subAssign(&g, makeZeckendorf()); printZeckendorf(g); printf(); g = makeZeckendorf(); subAssign(&g, makeZeckendorf()); printZeckendorf(g); printf(); printf(); g = makeZeckendorf(); mulAssign(&g, makeZeckendorf()); printZeckendorf(g); printf(); g = makeZeckendorf(); addAssign(&g, makeZeckendorf()); printZeckendorf(g); printf(); return 0; }
17Zeckendorf arithmetic
5c
2wlo
(def fibs (lazy-cat [1 1] (map + fibs (rest fibs)))) (defn z [n] (if (zero? n) "0" (let [ps (->> fibs (take-while #(<= % n)) rest reverse) fz (fn [[s n] p] (if (>= n p) [(conj s 1) (- n p)] [(conj s 0) n]))] (->> ps (reduce fz [[] n]) first (apply str))))) (doseq [n (range 0 21)] (println n (z n)))
16Zeckendorf number representation
6clojure
kths
use bigrat; foreach my $candidate (2 .. 2**19) { my $sum = 1 / $candidate; foreach my $factor (2 .. sqrt($candidate)+1) { if ($candidate % $factor == 0) { $sum += 1 / $factor + 1 / ($candidate / $factor); } } if ($sum->denominator() == 1) { print "Sum of recipr. factors of $candidate = $sum exactly ", ($sum == 1 ? "perfect!" : ""), "\n"; } }
8Arithmetic/Rational
2perl
6s36
package main import ( "bytes" "fmt" "strings" ) var in = ` 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000` func main() { b := wbFromString(in, '1') b.zhangSuen() fmt.Println(b) } const ( white = 0 black = 1 ) type wbArray [][]byte
15Zhang-Suen thinning algorithm
0go
0usk
require 'flt' include Flt BinNum.Context.precision = 512 def agm(a,g) new_a = BinNum a new_g = BinNum g while new_a - new_g > new_a.class.Context.epsilon do old_g = new_g new_g = (new_a * new_g).sqrt new_a = (old_g + new_a) * 0.5 end new_g end puts agm(1, 1 / BinNum(2).sqrt)
10Arithmetic-geometric mean
14ruby
msyj
sub ev {my $exp = shift; $exp =~ tr {0-9.+-/*()} {}cd; return ev_ast(astize($exp));} {my $balanced_paren_regex; $balanced_paren_regex = qr {\( ( [^()]+ | (??{$balanced_paren_regex}) )+ \)}x; sub astize {my $exp = shift; $exp =~ /[^0-9.]/ or return $exp; $exp = substr($exp, 1, -1) while $exp =~ /\A($balanced_paren_regex)\z/; my @paren_contents; $exp =~ s {($balanced_paren_regex)} {push(@paren_contents, $1); "[p$ $exp =~ m{(.+) ([+-]) (.+)}x or $exp =~ m{(.+) ([*/]) (.+)}x or die "Eh?: [$exp]\n"; my ($op, $lo, $ro) = ($2, $1, $3); s {\[p(\d+)\]} {($paren_contents[$1])}eg foreach $lo, $ro; return [$op, astize($lo), astize($ro)];}} {my %ops = ('+' => sub {$_[0] + $_[1]}, '-' => sub {$_[0] - $_[1]}, '*' => sub {$_[0] * $_[1]}, '/' => sub {$_[0] / $_[1]}); sub ev_ast {my $ast = shift; ref $ast or return $ast; my ($op, @operands) = @$ast; $_ = ev_ast($_) foreach @operands; return $ops{$op}->(@operands);}}
11Arithmetic evaluation
2perl
sgq3
def zhangSuen(text) { def image = text.split('\n').collect { line -> line.collect { it == '#' ? 1: 0} } def p2, p3, p4, p5, p6, p7, p8, p9 def step1 = { (p2 * p4 * p6 == 0) && (p4 * p6 * p8 == 0) } def step2 = { (p2 * p4 * p8 == 0) && (p2 * p6 * p8 == 0) } def reduce = { step -> def toWhite = [] image.eachWithIndex{ line, y -> line.eachWithIndex{ pixel, x -> if (!pixel) return (p2, p3, p4, p5, p6, p7, p8, p9) = [image[y-1][x], image[y-1][x+1], image[y][x+1], image[y+1][x+1], image[y+1][x], image[y+1][x-1], image[y][x-1], image[y-1][x-1]] def a = [[p2,p3],[p3,p4],[p4,p5],[p5,p6],[p6,p7],[p7,p8],[p8,p9],[p9,p2]].collect { a1, a2 -> (a1 == 0 && a2 ==1) ? 1: 0 }.sum() def b = [p2, p3, p4, p5, p6, p7, p8, p9].sum() if (a != 1 || b < 2 || b > 6) return if (step.call()) toWhite << [y,x] } } toWhite.each { y, x -> image[y][x] = 0 } !toWhite.isEmpty() } while (reduce(step1) | reduce(step2)); image.collect { line -> line.collect { it ? '#': '.' }.join('') }.join('\n') }
15Zhang-Suen thinning algorithm
7groovy
e9al
null
10Arithmetic-geometric mean
15rust
90mm
int main() { mpz_t a; mpz_init_set_ui(a, 5); mpz_pow_ui(a, a, 1 << 18); int len = mpz_sizeinbase(a, 10); printf(, len); char *s = mpz_get_str(0, 10, a); printf(, len = strlen(s)); printf(, s, s + len - 20); return 0; }
18Arbitrary-precision integers (included)
5c
n5i6
import Data.Array import qualified Data.List as List data BW = Black | White deriving (Eq, Show) type Index = (Int, Int) type BWArray = Array Index BW toBW :: Char -> BW toBW '0' = White toBW '1' = Black toBW ' ' = White toBW '#' = Black toBW _ = error "toBW: illegal char" toBWArray :: [String] -> BWArray toBWArray strings = arr where height = length strings width = minimum $ map length strings arr = listArray ((0, 0), (width - 1, height - 1)) . map toBW . concat . List.transpose $ map (take width) strings toChar :: BW -> Char toChar White = ' ' toChar Black = '#' chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = take n xs: (chunksOf n $ drop n xs) showBWArray :: BWArray -> String showBWArray arr = List.intercalate "\n" . List.transpose . chunksOf (height + 1) . map toChar $ elems arr where (_, (_, height)) = bounds arr add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d p2, p3, p4, p5, p6, p7, p8, p9 :: Index p2 = ( 0, -1) p3 = ( 1, -1) p4 = ( 1, 0) p5 = ( 1, 1) p6 = ( 0, 1) p7 = (-1, 1) p8 = (-1, 0) p9 = (-1, -1) ixamap :: Ix i => ((i, a) -> b) -> Array i a -> Array i b ixamap f a = listArray (bounds a) $ map f $ assocs a thin :: BWArray -> BWArray thin arr = if pass2 == arr then pass2 else thin pass2 where (low, high) = bounds arr lowB = low `add` (1, 1) highB = high `add` (-1, -1) isInner = within (lowB, highB) offs p = map (add p) [p2, p3, p4, p5, p6, p7, p8, p9] trans c (a, b) = if a == White && b == Black then c + 1 else c zipshift xs = zip xs (drop 1 xs ++ xs) transitions a = (== (1 :: Int)) . foldl trans 0 . zipshift . map (a !) . offs within2to6 n = 2 <= n && n <= 6 blacks a p = within2to6 . length . filter ((== Black) . (a !)) $ offs p oneWhite xs a p = any ((== White) . (a !) . add p) xs oneRight = oneWhite [p2, p4, p6] oneDown = oneWhite [p4, p6, p8] oneUp = oneWhite [p2, p4, p8] oneLeft = oneWhite [p2, p6, p8] precond a p = (a ! p == Black) && isInner p && blacks a p && transitions a p stage1 a p = precond a p && oneRight a p && oneDown a p stage2 a p = precond a p && oneUp a p && oneLeft a p stager f (p, d) = if f p then White else d pass1 = ixamap (stager $ stage1 arr) arr pass2 = ixamap (stager $ stage2 pass1) pass1 sampleExA :: [String] sampleExA = ["00000000000000000000000000000000" ,"01111111110000000111111110000000" ,"01110001111000001111001111000000" ,"01110000111000001110000111000000" ,"01110001111000001110000000000000" ,"01111111110000001110000000000000" ,"01110111100000001110000111000000" ,"01110011110011101111001111011100" ,"01110001111011100111111110011100" ,"00000000000000000000000000000000"] sampleExB :: [String] sampleExB = [" " ," ################# ############# " ," ################## ################ " ," ################### ################## " ," ######## ####### ################### " ," ###### ####### ####### ###### " ," ###### ####### ####### " ," ################# ####### " ," ################ ####### " ," ################# ####### " ," ###### ####### ####### " ," ###### ####### ####### " ," ###### ####### ####### ###### " ," ######## ####### ################### " ," ######## ####### ###### ################## ###### " ," ######## ####### ###### ################ ###### " ," ######## ####### ###### ############# ###### " ," "] main :: IO () main = mapM_ (putStrLn . showBWArray . thin . toBWArray) [sampleExA, sampleExB]
15Zhang-Suen thinning algorithm
8haskell
cw94
def agm(a: Double, g: Double, eps: Double): Double = { if (math.abs(a - g) < eps) (a + g) / 2 else agm((a + g) / 2, math.sqrt(a * g), eps) } agm(1, math.sqrt(2)/2, 1e-15)
10Arithmetic-geometric mean
16scala
2ilb
package main import ( "fmt" "strings" ) var ( dig = [3]string{"00", "01", "10"} dig1 = [3]string{"", "1", "10"} ) type Zeckendorf struct{ dVal, dLen int } func NewZeck(x string) *Zeckendorf { z := new(Zeckendorf) if x == "" { x = "0" } q := 1 i := len(x) - 1 z.dLen = i / 2 for ; i >= 0; i-- { z.dVal += int(x[i]-'0') * q q *= 2 } return z } func (z *Zeckendorf) a(i int) { for ; ; i++ { if z.dLen < i { z.dLen = i } j := (z.dVal >> uint(i*2)) & 3 switch j { case 0, 1: return case 2: if ((z.dVal >> (uint(i+1) * 2)) & 1) != 1 { return } z.dVal += 1 << uint(i*2+1) return case 3: z.dVal &= ^(3 << uint(i*2)) z.b((i + 1) * 2) } } } func (z *Zeckendorf) b(pos int) { if pos == 0 { z.Inc() return } if ((z.dVal >> uint(pos)) & 1) == 0 { z.dVal += 1 << uint(pos) z.a(pos / 2) if pos > 1 { z.a(pos/2 - 1) } } else { z.dVal &= ^(1 << uint(pos)) z.b(pos + 1) temp := 1 if pos > 1 { temp = 2 } z.b(pos - temp) } } func (z *Zeckendorf) c(pos int) { if ((z.dVal >> uint(pos)) & 1) == 1 { z.dVal &= ^(1 << uint(pos)) return } z.c(pos + 1) if pos > 0 { z.b(pos - 1) } else { z.Inc() } } func (z *Zeckendorf) Inc() { z.dVal++ z.a(0) } func (z1 *Zeckendorf) PlusAssign(z2 *Zeckendorf) { for gn := 0; gn < (z2.dLen+1)*2; gn++ { if ((z2.dVal >> uint(gn)) & 1) == 1 { z1.b(gn) } } } func (z1 *Zeckendorf) MinusAssign(z2 *Zeckendorf) { for gn := 0; gn < (z2.dLen+1)*2; gn++ { if ((z2.dVal >> uint(gn)) & 1) == 1 { z1.c(gn) } } for z1.dLen > 0 && ((z1.dVal>>uint(z1.dLen*2))&3) == 0 { z1.dLen-- } } func (z1 *Zeckendorf) TimesAssign(z2 *Zeckendorf) { na := z2.Copy() nb := z2.Copy() nr := new(Zeckendorf) for i := 0; i <= (z1.dLen+1)*2; i++ { if ((z1.dVal >> uint(i)) & 1) > 0 { nr.PlusAssign(nb) } nt := nb.Copy() nb.PlusAssign(na) na = nt.Copy() } z1.dVal = nr.dVal z1.dLen = nr.dLen } func (z *Zeckendorf) Copy() *Zeckendorf { return &Zeckendorf{z.dVal, z.dLen} } func (z1 *Zeckendorf) Compare(z2 *Zeckendorf) int { switch { case z1.dVal < z2.dVal: return -1 case z1.dVal > z2.dVal: return 1 default: return 0 } } func (z *Zeckendorf) String() string { if z.dVal == 0 { return "0" } var sb strings.Builder sb.WriteString(dig1[(z.dVal>>uint(z.dLen*2))&3]) for i := z.dLen - 1; i >= 0; i-- { sb.WriteString(dig[(z.dVal>>uint(i*2))&3]) } return sb.String() } func main() { fmt.Println("Addition:") g := NewZeck("10") g.PlusAssign(NewZeck("10")) fmt.Println(g) g.PlusAssign(NewZeck("10")) fmt.Println(g) g.PlusAssign(NewZeck("1001")) fmt.Println(g) g.PlusAssign(NewZeck("1000")) fmt.Println(g) g.PlusAssign(NewZeck("10101")) fmt.Println(g) fmt.Println("\nSubtraction:") g = NewZeck("1000") g.MinusAssign(NewZeck("101")) fmt.Println(g) g = NewZeck("10101010") g.MinusAssign(NewZeck("1010101")) fmt.Println(g) fmt.Println("\nMultiplication:") g = NewZeck("1001") g.TimesAssign(NewZeck("101")) fmt.Println(g) g = NewZeck("101010") g.PlusAssign(NewZeck("101")) fmt.Println(g) }
17Zeckendorf arithmetic
0go
qcxz
package main import "fmt" func getDivisors(n int) []int { divs := []int{1, n} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs = append(divs, j) } } } return divs } func sum(divs []int) int { sum := 0 for _, div := range divs { sum += div } return sum } func isPartSum(divs []int, sum int) bool { if sum == 0 { return true } le := len(divs) if le == 0 { return false } last := divs[le-1] divs = divs[0 : le-1] if last > sum { return isPartSum(divs, sum) } return isPartSum(divs, sum) || isPartSum(divs, sum-last) } func isZumkeller(n int) bool { divs := getDivisors(n) sum := sum(divs)
19Zumkeller numbers
0go
f4d0
import Data.List (find, mapAccumL) import Control.Arrow (first, second) fibs :: Num a => a -> a -> [a] fibs a b = res where res = a: b: zipWith (+) res (tail res) data Fib = Fib { sign :: Int, digits :: [Int]} mkFib s ds = case dropWhile (==0) ds of [] -> 0 ds -> Fib s (reverse ds) instance Show Fib where show (Fib s ds) = sig s ++ foldMap show (reverse ds) where sig = \case { -1 -> "-"; s -> "" } instance Eq Fib where Fib sa a == Fib sb b = sa == sb && a == b instance Ord Fib where a `compare` b = sign a `compare` sign b <> case find (/= 0) $ alignWith (-) (digits a) (digits b) of Nothing -> EQ Just 1 -> if sign a > 0 then GT else LT Just (-1) -> if sign a > 0 then LT else GT instance Num Fib where negate (Fib s ds) = Fib (negate s) ds abs (Fib s ds) = Fib 1 ds signum (Fib s _) = fromIntegral s fromInteger n = case compare n 0 of LT -> negate $ fromInteger (- n) EQ -> Fib 0 [0] GT -> Fib 1 . reverse . fst $ divModFib n 1 0 + a = a a + 0 = a a + b = case (sign a, sign b) of ( 1, 1) -> res (-1, 1) -> b - (-a) ( 1,-1) -> a - (-b) (-1,-1) -> - ((- a) + (- b)) where res = mkFib 1 . process $ 0:0:c c = alignWith (+) (digits a) (digits b) process = runRight 3 r2 . runLeftR 3 r2 . runRightR 4 r1 0 - a = -a a - 0 = a a - b = case (sign a, sign b) of ( 1, 1) -> res (-1, 1) -> - ((-a) + b) ( 1,-1) -> a + (-b) (-1,-1) -> - ((-a) - (-b)) where res = case find (/= 0) c of Just 1 -> mkFib 1 . process $ c Just (-1) -> - (b - a) Nothing -> 0 c = alignWith (-) (digits a) (digits b) process = runRight 3 r2 . runLeftR 3 r2 . runRightR 4 r1 . runRight 3 r3 0 * a = 0 a * 0 = 0 1 * a = a a * 1 = a a * b = case (sign a, sign b) of (1, 1) -> res (-1, 1) -> - ((-a) * b) ( 1,-1) -> - (a * (-b)) (-1,-1) -> ((-a) * (-b)) where table = fibs a (a + a) res = sum $ onlyOnes $ zip (digits b) table onlyOnes = map snd . filter ((==1) . fst) instance Enum Fib where toEnum = fromInteger . fromIntegral fromEnum = fromIntegral . toInteger instance Real Fib where toRational = fromInteger . toInteger instance Integral Fib where toInteger (Fib s ds) = signum (fromIntegral s) * res where res = sum (zipWith (*) (fibs 1 2) (fromIntegral <$> ds)) quotRem 0 _ = (0, 0) quotRem a 0 = error "divide by zero" quotRem a b = case (sign a, sign b) of (1, 1) -> first (mkFib 1) $ divModFib a b (-1, 1) -> second negate . first negate $ quotRem (-a) b ( 1,-1) -> first negate $ quotRem a (-b) (-1,-1) -> second negate $ quotRem (-a) (-b) divModFib :: (Ord a, Num c, Num a) => a -> a -> ([c], a) divModFib a b = (q, r) where (r, q) = mapAccumL f a $ reverse $ takeWhile (<= a) table table = fibs b (b+b) f n x = if n < x then (n, 0) else (n - x, 1) runRight n f = go where go [] = [] go lst = let (w, r) = splitAt n lst (h: t) = f w in h: go (t ++ r) runRightR n f = go [] where go res [] = res go res lst = let (w, r) = splitAt n lst (h: t) = f w in go (h: res) (t ++ r) runLeftR n f = runRightR n (reverse . f . reverse) r1 = \case [0,3,0] -> [1,1,1] [0,2,0] -> [1,0,1] [0,1,2] -> [1,0,1] [0,2,1] -> [1,1,0] [x,0,2] -> [x,1,0] [x,0,3] -> [x,1,1] [0,1,2,0] -> [1,0,1,0] [0,2,0,x] -> [1,0,0,x+1] [0,3,0,x] -> [1,1,0,x+1] [0,2,1,x] -> [1,1,0,x ] [0,1,2,x] -> [1,0,1,x ] l -> l r2 = \case [0,1,1] -> [1,0,0] l -> l r3 = \case [1,-1] -> [0,1] [2,-1] -> [1,1] [1, 0, 0] -> [0,1,1] [1,-1, 0] -> [0,0,1] [1,-1, 1] -> [0,0,2] [1, 0,-1] -> [0,1,0] [2, 0, 0] -> [1,1,1] [2,-1, 0] -> [1,0,1] [2,-1, 1] -> [1,0,2] [2, 0,-1] -> [1,1,0] l -> l alignWith :: (Int -> Int -> a) -> [Int] -> [Int] -> [a] alignWith f a b = go [] a b where go res as [] = ((`f` 0) <$> reverse as) ++ res go res [] bs = ((0 `f`) <$> reverse bs) ++ res go res (a:as) (b:bs) = go (f a b: res) as bs
17Zeckendorf arithmetic
8haskell
mpyf
import Data.List (group, sort) import Data.List.Split (chunksOf) import Data.Numbers.Primes (primeFactors) isZumkeller :: Int -> Bool isZumkeller n = let ds = divisors n m = sum ds in ( even m && let half = div m 2 in elem half ds || ( all (half >=) ds && summable half ds ) ) summable :: Int -> [Int] -> Bool summable _ [] = False summable x xs@(h: t) = elem x xs || summable (x - h) t || summable x t divisors :: Int -> [Int] divisors x = sort ( foldr ( flip ((<*>) . fmap (*)) . scanl (*) 1 ) [1] (group (primeFactors x)) ) main :: IO () main = mapM_ ( \(s, n, xs) -> putStrLn $ s <> ( '\n': tabulated 10 (take n (filter isZumkeller xs)) ) ) [ ("First 220 Zumkeller numbers:", 220, [1 ..]), ("First 40 odd Zumkeller numbers:", 40, [1, 3 ..]) ] tabulated :: Show a => Int -> [a] -> String tabulated nCols = go where go xs = let ts = show <$> xs w = succ (maximum (length <$> ts)) in unlines ( concat <$> chunksOf nCols (justifyRight w ' ' <$> ts) ) justifyRight :: Int -> Char -> String -> String justifyRight n c = (drop . length) <*> (replicate n c <>)
19Zumkeller numbers
8haskell
4q5s
(defn exp [n k] (reduce * (repeat k n))) (def big (->> 2 (exp 3) (exp 4) (exp 5))) (def sbig (str big)) (assert (= "62060698786608744707" (.substring sbig 0 20))) (assert (= "92256259918212890625" (.substring sbig (- (count sbig) 20)))) (println (count sbig) "digits") (println (str (.substring sbig 0 20) ".." (.substring sbig (- (count sbig) 20))) (str "(" (count sbig) " digits)"))
18Arbitrary-precision integers (included)
6clojure
3jzr
import java.awt.Point; import java.util.*; public class ZhangSuen { final static String[] image = { " ", " ################# ############# ", " ################## ################ ", " ################### ################## ", " ######## ####### ################### ", " ###### ####### ####### ###### ", " ###### ####### ####### ", " ################# ####### ", " ################ ####### ", " ################# ####### ", " ###### ####### ####### ", " ###### ####### ####### ", " ###### ####### ####### ###### ", " ######## ####### ################### ", " ######## ####### ###### ################## ###### ", " ######## ####### ###### ################ ###### ", " ######## ####### ###### ############# ###### ", " "}; final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}}; final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6}, {0, 4, 6}}}; static List<Point> toWhite = new ArrayList<>(); static char[][] grid; public static void main(String[] args) { grid = new char[image.length][]; for (int r = 0; r < image.length; r++) grid[r] = image[r].toCharArray(); thinImage(); } static void thinImage() { boolean firstStep = false; boolean hasChanged; do { hasChanged = false; firstStep = !firstStep; for (int r = 1; r < grid.length - 1; r++) { for (int c = 1; c < grid[0].length - 1; c++) { if (grid[r][c] != '#') continue; int nn = numNeighbors(r, c); if (nn < 2 || nn > 6) continue; if (numTransitions(r, c) != 1) continue; if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1)) continue; toWhite.add(new Point(c, r)); hasChanged = true; } } for (Point p : toWhite) grid[p.y][p.x] = ' '; toWhite.clear(); } while (firstStep || hasChanged); printResult(); } static int numNeighbors(int r, int c) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#') count++; return count; } static int numTransitions(int r, int c) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') { if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#') count++; } return count; } static boolean atLeastOneIsWhite(int r, int c, int step) { int count = 0; int[][] group = nbrGroups[step]; for (int i = 0; i < 2; i++) for (int j = 0; j < group[i].length; j++) { int[] nbr = nbrs[group[i][j]]; if (grid[r + nbr[1]][c + nbr[0]] == ' ') { count++; break; } } return count > 1; } static void printResult() { for (char[] row : grid) System.out.println(row); } }
15Zhang-Suen thinning algorithm
9java
zktq
from fractions import Fraction for candidate in range(2, 2**19): sum = Fraction(1, candidate) for factor in range(2, int(candidate**0.5)+1): if candidate% factor == 0: sum += Fraction(1, factor) + Fraction(1, candidate if sum.denominator == 1: print(% (candidate, int(sum), if sum == 1 else ))
8Arithmetic/Rational
3python
y06q
import operator class AstNode(object): def __init__( self, opr, left, right ): self.opr = opr self.l = left self.r = right def eval(self): return self.opr(self.l.eval(), self.r.eval()) class LeafNode(object): def __init__( self, valStrg ): self.v = int(valStrg) def eval(self): return self.v class Yaccer(object): def __init__(self): self.operstak = [] self.nodestak =[] self.__dict__.update(self.state1) def v1( self, valStrg ): self.nodestak.append( LeafNode(valStrg)) self.__dict__.update(self.state2) def o2( self, operchar ): def openParen(a,b): return 0 opDict= { '+': ( operator.add, 2, 2 ), '-': (operator.sub, 2, 2 ), '*': (operator.mul, 3, 3 ), '/': (operator.div, 3, 3 ), '^': ( pow, 4, 5 ), '(': ( openParen, 0, 8 ) } operPrecidence = opDict[operchar][2] self.redeuce(operPrecidence) self.operstak.append(opDict[operchar]) self.__dict__.update(self.state1) def syntaxErr(self, char ): print 'parse error - near operator '%char def pc2( self,operchar ): self.redeuce( 1 ) if len(self.operstak)>0: self.operstak.pop() else: print 'Error - no open parenthesis matches close parens.' self.__dict__.update(self.state2) def end(self): self.redeuce(0) return self.nodestak.pop() def redeuce(self, precidence): while len(self.operstak)>0: tailOper = self.operstak[-1] if tailOper[1] < precidence: break tailOper = self.operstak.pop() vrgt = self.nodestak.pop() vlft= self.nodestak.pop() self.nodestak.append( AstNode(tailOper[0], vlft, vrgt)) state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr } state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 } def Lex( exprssn, p ): bgn = None cp = -1 for c in exprssn: cp += 1 if c in '+-/*^()': if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None if c=='(': p.po(p, c) elif c==')':p.pc(p, c) else: p.o(p, c) elif c in ' \t': if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None elif c in '0123456789': if bgn is None: bgn = cp else: print 'Invalid character in expression' if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None if bgn is not None: p.v(p, exprssn[bgn:cp+1]) bgn = None return p.end() expr = raw_input() astTree = Lex( expr, Yaccer()) print expr, '=',astTree.eval()
11Arithmetic evaluation
3python
0rsq
import java.util.List; public class Zeckendorf implements Comparable<Zeckendorf> { private static List<String> dig = List.of("00", "01", "10"); private static List<String> dig1 = List.of("", "1", "10"); private String x; private int dVal = 0; private int dLen = 0; public Zeckendorf() { this("0"); } public Zeckendorf(String x) { this.x = x; int q = 1; int i = x.length() - 1; dLen = i / 2; while (i >= 0) { dVal += (x.charAt(i) - '0') * q; q *= 2; i--; } } private void a(int n) { int i = n; while (true) { if (dLen < i) dLen = i; int j = (dVal >> (i * 2)) & 3; switch (j) { case 0: case 1: return; case 2: if (((dVal >> ((i + 1) * 2)) & 1) != 1) return; dVal += 1 << (i * 2 + 1); return; case 3: int temp = 3 << (i * 2); temp ^= -1; dVal = dVal & temp; b((i + 1) * 2); break; } i++; } } private void b(int pos) { if (pos == 0) { Zeckendorf thiz = this; thiz.inc(); return; } if (((dVal >> pos) & 1) == 0) { dVal += 1 << pos; a(pos / 2); if (pos > 1) a(pos / 2 - 1); } else { int temp = 1 << pos; temp ^= -1; dVal = dVal & temp; b(pos + 1); b(pos - (pos > 1 ? 2 : 1)); } } private void c(int pos) { if (((dVal >> pos) & 1) == 1) { int temp = 1 << pos; temp ^= -1; dVal = dVal & temp; return; } c(pos + 1); if (pos > 0) { b(pos - 1); } else { Zeckendorf thiz = this; thiz.inc(); } } public Zeckendorf inc() { dVal++; a(0); return this; } public void plusAssign(Zeckendorf other) { for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) { if (((other.dVal >> gn) & 1) == 1) { b(gn); } } } public void minusAssign(Zeckendorf other) { for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) { if (((other.dVal >> gn) & 1) == 1) { c(gn); } } while ((((dVal >> dLen * 2) & 3) == 0) || (dLen == 0)) { dLen--; } } public void timesAssign(Zeckendorf other) { Zeckendorf na = other.copy(); Zeckendorf nb = other.copy(); Zeckendorf nt; Zeckendorf nr = new Zeckendorf(); for (int i = 0; i < (dLen + 1) * 2; i++) { if (((dVal >> i) & 1) > 0) { nr.plusAssign(nb); } nt = nb.copy(); nb.plusAssign(na); na = nt.copy(); } dVal = nr.dVal; dLen = nr.dLen; } private Zeckendorf copy() { Zeckendorf z = new Zeckendorf(); z.dVal = dVal; z.dLen = dLen; return z; } @Override public int compareTo(Zeckendorf other) { return ((Integer) dVal).compareTo(other.dVal); } @Override public String toString() { if (dVal == 0) { return "0"; } int idx = (dVal >> (dLen * 2)) & 3; StringBuilder stringBuilder = new StringBuilder(dig1.get(idx)); for (int i = dLen - 1; i >= 0; i--) { idx = (dVal >> (i * 2)) & 3; stringBuilder.append(dig.get(idx)); } return stringBuilder.toString(); } public static void main(String[] args) { System.out.println("Addition:"); Zeckendorf g = new Zeckendorf("10"); g.plusAssign(new Zeckendorf("10")); System.out.println(g); g.plusAssign(new Zeckendorf("10")); System.out.println(g); g.plusAssign(new Zeckendorf("1001")); System.out.println(g); g.plusAssign(new Zeckendorf("1000")); System.out.println(g); g.plusAssign(new Zeckendorf("10101")); System.out.println(g); System.out.println("\nSubtraction:"); g = new Zeckendorf("1000"); g.minusAssign(new Zeckendorf("101")); System.out.println(g); g = new Zeckendorf("10101010"); g.minusAssign(new Zeckendorf("1010101")); System.out.println(g); System.out.println("\nMultiplication:"); g = new Zeckendorf("1001"); g.timesAssign(new Zeckendorf("101")); System.out.println(g); g = new Zeckendorf("101010"); g.plusAssign(new Zeckendorf("101")); System.out.println(g); } }
17Zeckendorf arithmetic
9java
frdv
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ZumkellerNumbers { public static void main(String[] args) { int n = 1; System.out.printf("First 220 Zumkeller numbers:%n"); for ( int count = 1 ; count <= 220 ; n += 1 ) { if ( isZumkeller(n) ) { System.out.printf("%3d ", n); if ( count % 20 == 0 ) { System.out.printf("%n"); } count++; } } n = 1; System.out.printf("%nFirst 40 odd Zumkeller numbers:%n"); for ( int count = 1 ; count <= 40 ; n += 2 ) { if ( isZumkeller(n) ) { System.out.printf("%6d", n); if ( count % 10 == 0 ) { System.out.printf("%n"); } count++; } } n = 1; System.out.printf("%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n"); for ( int count = 1 ; count <= 40 ; n += 2 ) { if ( n % 5 != 0 && isZumkeller(n) ) { System.out.printf("%8d", n); if ( count % 10 == 0 ) { System.out.printf("%n"); } count++; } } } private static boolean isZumkeller(int n) {
19Zumkeller numbers
9java
cp9h
function Point(x, y) { this.x = x; this.y = y; } var ZhangSuen = (function () { function ZhangSuen() { } ZhangSuen.image = [" ", " ################# ############# ", " ################## ################ ", " ################### ################## ", " ######## ####### ################### ", " ###### ####### ####### ###### ", " ###### ####### ####### ", " ################# ####### ", " ################ ####### ", " ################# ####### ", " ###### ####### ####### ", " ###### ####### ####### ", " ###### ####### ####### ###### ", " ######## ####### ################### ", " ######## ####### ###### ################## ###### ", " ######## ####### ###### ################ ###### ", " ######## ####### ###### ############# ###### ", " "]; ZhangSuen.nbrs = [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1]]; ZhangSuen.nbrGroups = [[[0, 2, 4], [2, 4, 6]], [[0, 2, 6], [0, 4, 6]]]; ZhangSuen.toWhite = new Array(); ; ZhangSuen.main = function (args) { ZhangSuen.grid = new Array(ZhangSuen.image.length); for (var r = 0; r < ZhangSuen.image.length; r++) ZhangSuen.grid[r] = (ZhangSuen.image[r]).split(''); ZhangSuen.thinImage(); }; ZhangSuen.thinImage = function () { var firstStep = false; var hasChanged; do { hasChanged = false; firstStep = !firstStep; for (var r = 1; r < ZhangSuen.grid.length - 1; r++) { for (var c = 1; c < ZhangSuen.grid[0].length - 1; c++) { if (ZhangSuen.grid[r][c] !== '#') continue; var nn = ZhangSuen.numNeighbors(r, c); if (nn < 2 || nn > 6) continue; if (ZhangSuen.numTransitions(r, c) !== 1) continue; if (!ZhangSuen.atLeastOneIsWhite(r, c, firstStep ? 0 : 1)) continue; ZhangSuen.toWhite.push(new Point(c, r)); hasChanged = true; } } for (let i = 0; i < ZhangSuen.toWhite.length; i++) { var p = ZhangSuen.toWhite[i]; ZhangSuen.grid[p.y][p.x] = ' '; } ZhangSuen.toWhite = new Array(); } while ((firstStep || hasChanged)); ZhangSuen.printResult(); }; ZhangSuen.numNeighbors = function (r, c) { var count = 0; for (var i = 0; i < ZhangSuen.nbrs.length - 1; i++) if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === '#') count++; return count; }; ZhangSuen.numTransitions = function (r, c) { var count = 0; for (var i = 0; i < ZhangSuen.nbrs.length - 1; i++) if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === ' ') { if (ZhangSuen.grid[r + ZhangSuen.nbrs[i + 1][1]][c + ZhangSuen.nbrs[i + 1][0]] === '#') count++; } return count; }; ZhangSuen.atLeastOneIsWhite = function (r, c, step) { var count = 0; var group = ZhangSuen.nbrGroups[step]; for (var i = 0; i < 2; i++) for (var j = 0; j < group[i].length; j++) { var nbr = ZhangSuen.nbrs[group[i][j]]; if (ZhangSuen.grid[r + nbr[1]][c + nbr[0]] === ' ') { count++; break; } } return count > 1; }; ZhangSuen.printResult = function () { for (var i = 0; i < ZhangSuen.grid.length; i++) { var row = ZhangSuen.grid[i]; console.log(row.join('')); } }; return ZhangSuen; }()); ZhangSuen.main(null);
15Zhang-Suen thinning algorithm
10javascript
9eml
null
17Zeckendorf arithmetic
11kotlin
8v0q
use Math::Complex; my $a = 1 + 1*i; my $b = 3.14159 + 1.25*i; print "$_\n" foreach $a + $b, $a * $b, -$a, 1 / $a, ~$a;
9Arithmetic/Complex
2perl
npiw
WITH rec (rn, a, g, diff) AS ( SELECT 1, 1, 1/SQRT(2), 1 - 1/SQRT(2) FROM dual UNION ALL SELECT rn + 1, (a + g)/2, SQRT(a * g), (a + g)/2 - SQRT(a * g) FROM rec WHERE diff > 1e-38 ) SELECT * FROM rec WHERE diff <= 1e-38 ;
10Arithmetic-geometric mean
19sql
5fu3
package main import ( "fmt" "math" "math/big" "math/cmplx" ) func main() { fmt.Println("float64: ", math.Pow(0, 0)) var b big.Int fmt.Println("big integer:", b.Exp(&b, &b, nil)) fmt.Println("complex: ", cmplx.Pow(0, 0)) }
14Zero to the zero power
0go
suqa
println 0**0
14Zero to the zero power
7groovy
a91p
typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf(, it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
20Yellowstone sequence
5c
at11
import java.util.ArrayList import kotlin.math.sqrt object ZumkellerNumbers { @JvmStatic fun main(args: Array<String>) { var n = 1 println("First 220 Zumkeller numbers:") run { var count = 1 while (count <= 220) { if (isZumkeller(n)) { print("%3d ".format(n)) if (count % 20 == 0) { println() } count++ } n += 1 } } n = 1 println("\nFirst 40 odd Zumkeller numbers:") run { var count = 1 while (count <= 40) { if (isZumkeller(n)) { print("%6d".format(n)) if (count % 10 == 0) { println() } count++ } n += 2 } } n = 1 println("\nFirst 40 odd Zumkeller numbers that do not end in a 5:") var count = 1 while (count <= 40) { if (n % 5 != 0 && isZumkeller(n)) { print("%8d".format(n)) if (count % 10 == 0) { println() } count++ } n += 2 } } private fun isZumkeller(n: Int): Boolean {
19Zumkeller numbers
11kotlin
37z5
import 'dart:math' show pow; int fallingPowers(int base) => base == 1? 1: pow(base, fallingPowers(base - 1)); void main() { final exponent = fallingPowers(4), s = BigInt.from(5).pow(exponent).toString(); print('First twenty: ${s.substring(0, 20)}'); print('Last twenty: ${s.substring(s.length - 20)}'); print('Number of digits: ${s.length}');
18Arbitrary-precision integers (included)
18dart
q9xo
null
15Zhang-Suen thinning algorithm
11kotlin
igo4
int main() { char is_open[100] = { 0 }; int pass, door; for (pass = 0; pass < 100; ++pass) for (door = pass; door < 100; door += pass+1) is_open[door] = !is_open[door]; for (door = 0; door < 100; ++door) printf(, door+1, (is_open[door]? : )); return 0; }
21100 doors
5c
ilo2
import Darwin enum AGRError: Error { case undefined } func agm(_ a: Double, _ g: Double, _ iota: Double = 1e-8) throws -> Double { var a = a var g = g var a1: Double = 0 var g1: Double = 0 guard a * g >= 0 else { throw AGRError.undefined } while abs(a - g) > iota { a1 = (a + g) / 2 g1 = sqrt(a * g) a = a1 g = g1 } return a } do { try print(agm(1, 1 / sqrt(2))) } catch { print("agr is undefined when a * g < 0") }
10Arithmetic-geometric mean
17swift
yq6e
import Data.Complex main = do print $ 0 ^ 0 print $ 0.0 ^ 0 print $ 0 ^^ 0 print $ 0 ** 0 print $ (0:+ 0) ^ 0 print $ (0:+ 0) ** (0:+ 0)
14Zero to the zero power
8haskell
9wmo
$op_priority = { => 0, => 0, => 1, => 1} class TreeNode OP_FUNCTION = { => lambda {|x, y| x + y}, => lambda {|x, y| x - y}, => lambda {|x, y| x * y}, => lambda {|x, y| x / y}} attr_accessor :info, :left, :right def initialize(info) @info = info end def leaf? @left.nil? and @right.nil? end def to_s(order) if leaf? @info else left_s, right_s = @left.to_s(order), @right.to_s(order) strs = case order when :prefix then [@info, left_s, right_s] when :infix then [left_s, @info, right_s] when :postfix then [left_s, right_s, @info] else [] end + strs.join() + end end def eval if!leaf? and operator?(@info) OP_FUNCTION[@info].call(@left.eval, @right.eval) else @info.to_f end end end def tokenize(exp) exp .gsub('(', ' ( ') .gsub(')', ' ) ') .gsub('+', ' + ') .gsub('-', ' - ') .gsub('*', ' * ') .gsub('/', ' / ') .split(' ') end def operator?(token) $op_priority.has_key?(token) end def pop_connect_push(op_stack, node_stack) temp = op_stack.pop temp.right = node_stack.pop temp.left = node_stack.pop node_stack.push(temp) end def infix_exp_to_tree(exp) tokens = tokenize(exp) op_stack, node_stack = [], [] tokens.each do |token| if operator?(token) until (op_stack.empty? or op_stack.last.info == or $op_priority[op_stack.last.info] < $op_priority[token]) pop_connect_push(op_stack, node_stack) end op_stack.push(TreeNode.new(token)) elsif token == op_stack.push(TreeNode.new(token)) elsif token == while op_stack.last.info!= pop_connect_push(op_stack, node_stack) end op_stack.pop else node_stack.push(TreeNode.new(token)) end end until op_stack.empty? pop_connect_push(op_stack, node_stack) end node_stack.last end
11Arithmetic evaluation
14ruby
oj8v
use strict; use warnings; for ( split /\n/, <<END ) 1 + 1 10 + 10 10100 + 1010 10100 - 1010 10100 * 1010 100010 * 100101 10100 / 1010 101000 / 1000 100001000001 / 100010 100001000001 / 100101 END { my ($left, $op, $right) = split; my ($x, $y) = map Zeckendorf->new($_), $left, $right; my $answer = $op eq '+' ? $x + $y : $op eq '-' ? $x - $y : $op eq '*' ? $x * $y : $op eq '/' ? $x / $y : die "bad op <$op>"; printf "%12s%s%-9s =>%12s in Zeckendorf\n", $x, $op, $y, $answer; printf "%12d%s%-9d =>%12d in decimal\n\n", $x->asdecimal, $op, $y->asdecimal, $answer->asdecimal; } package Zeckendorf; use overload qw("" zstring + zadd - zsub ++ zinc -- zdec * zmul / zdiv ge zge); sub new { my ($class, $value) = @_; bless \$value, ref $class || $class; } sub zinc { my ($self, $other, $swap) = @_; local $_ = $$self; s/0$/1/ or s/(?:^|0)1$/10/; 1 while s/(?:^|0)11/100/; $_[0] = $self->new( s/^0+\B//r ); } sub zdec { my ($self, $other, $swap) = @_; local $_ = $$self; 1 while s/100(?=0*$)/011/; s/1$/0/ or s/10$/01/; $_[0] = $self->new( s/^0+\B//r ); } sub zstring { ${ shift() } } sub zadd { my ($self, $other, $swap) = @_; my ($x, $y) = map $self->new($$_), $self, $other; ++$x, $y-- while $$y ne 0; return $x; } sub zsub { my ($self, $other, $swap) = @_; my ($x, $y) = map $self->new($$_), $self, $other; --$x, $y-- while $$y ne 0; return $x; } sub zmul { my ($self, $other, $swap) = @_; my ($x, $y) = map $self->new($$_), $self, $other; my $product = Zeckendorf->new(0); $product = $product + $x, --$y while "$y" ne 0; return $product; } sub zdiv { my ($self, $other, $swap) = @_; my ($x, $y) = map $self->new($$_), $self, $other; my $quotient = Zeckendorf->new(0); ++$quotient, $x = $x - $y while $x ge $y; return $quotient; } sub zge { my ($self, $other, $swap) = @_; my $l = length( $$self | $$other ); 0 x ($l - length $$self) . $$self ge 0 x ($l - length $$other) . $$other; } sub asdecimal { my ($self) = @_; my $n = 0; my $aa = my $bb = 1; for ( reverse split //, $$self ) { $n += $bb * $_; ($aa, $bb) = ($bb, $aa + $bb); } return $n; } sub fromdecimal { my ($self, $value) = @_; my $z = $self->new(0); ++$z for 1 .. $value; return $z; }
17Zeckendorf arithmetic
2perl
405d
function zhangSuenThin(img) local dirs={ { 0,-1}, { 1,-1}, { 1, 0}, { 1, 1}, { 0, 1}, {-1, 1}, {-1, 0}, {-1,-1}, { 0,-1}, } local black=1 local white=0 function A(x, y) local c=0 local current=img[y+dirs[1][2]][x+dirs[1][1]] for i=2,#dirs do local to_compare=img[y+dirs[i][2]][x+dirs[i][1]] if current==white and to_compare==black then c=c+1 end current=to_compare end return c end function B(x, y) local c=0 for i=2,#dirs do local value=img[y+dirs[i][2]][x+dirs[i][1]] if value==black then c=c+1 end end return c end function common_step(x, y) if img[y][x]~=black or x<=1 or x>=#img[y] or y<=1 or y>=#img then return false end local b_value=B(x, y) if b_value<2 or b_value>6 then return false end local a_value=A(x, y) if a_value~=1 then return false end return true end function step_one(x, y) if not common_step(x, y) then return false end local p2=img[y+dirs[1][2]][x+dirs[1][1]] local p4=img[y+dirs[3][2]][x+dirs[3][1]] local p6=img[y+dirs[5][2]][x+dirs[5][1]] local p8=img[y+dirs[7][2]][x+dirs[7][1]] if p4==white or p6==white or p2==white and p8==white then return true end return false end function step_two(x, y) if not common_step(x, y) then return false end local p2=img[y+dirs[1][2]][x+dirs[1][1]] local p4=img[y+dirs[3][2]][x+dirs[3][1]] local p6=img[y+dirs[5][2]][x+dirs[5][1]] local p8=img[y+dirs[7][2]][x+dirs[7][1]] if p2==white or p8==white or p4==white and p6==white then return true end return false end function convert(to_do) for k,v in pairs(to_do) do img[v[2]][v[1]]=white end end function do_step_on_all(step) local to_convert={} for y=1,#img do for x=1,#img[y] do if step(x, y) then table.insert(to_convert, {x,y}) end end end convert(to_convert) return #to_convert>0 end local continue=true while continue do continue=false if do_step_on_all(step_one) then continue=true end if do_step_on_all(step_two) then continue=true end end for y=1,#img do for x=1,#img[y] do io.write(img[y][x]==black and '#' or ' ') end io.write('\n') end end local image = { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0}, {0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,0,0,0,0}, {0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0}, {0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0}, {0,1,1,1,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,0,1,1,1,0,0}, {0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, } zhangSuenThin(image)
15Zhang-Suen thinning algorithm
1lua
nri8
null
11Arithmetic evaluation
15rust
ihod
for candidate in 2 .. 2**19 sum = Rational(1, candidate) for factor in 2 .. Integer.sqrt(candidate) if candidate % factor == 0 sum += Rational(1, factor) + Rational(1, candidate / factor) end end if sum.denominator == 1 puts % [candidate, sum.to_i, sum == 1? : ] end end
8Arithmetic/Rational
14ruby
9omz
System.out.println(Math.pow(0, 0));
14Zero to the zero power
9java
tkf9
package org.rosetta.arithmetic_evaluator.scala object ArithmeticParser extends scala.util.parsing.combinator.RegexParsers { def readExpression(input: String) : Option[()=>Int] = { parseAll(expr, input) match { case Success(result, _) => Some(result) case other => println(other) None } } private def expr : Parser[()=>Int] = { (term<~"+")~expr ^^ { case l~r => () => l() + r() } | (term<~"-")~expr ^^ { case l~r => () => l() - r() } | term } private def term : Parser[()=>Int] = { (factor<~"*")~term ^^ { case l~r => () => l() * r() } | (factor<~"/")~term ^^ { case l~r => () => l() / r() } | factor } private def factor : Parser[()=>Int] = { "("~>expr<~")" | "\\d+".r ^^ { x => () => x.toInt } | failure("Expected a value") } } object Main { def main(args: Array[String]) { println("""Please input the expressions. Type "q" to quit.""") var input: String = "" do { input = readLine("> ") if (input != "q") { ArithmeticParser.readExpression(input).foreach(f => println(f())) } } while (input != "q") } }
11Arithmetic evaluation
16scala
fpd4
import copy class Zeckendorf: def __init__(self, x='0'): q = 1 i = len(x) - 1 self.dLen = int(i / 2) self.dVal = 0 while i >= 0: self.dVal = self.dVal + (ord(x[i]) - ord('0')) * q q = q * 2 i = i -1 def a(self, n): i = n while True: if self.dLen < i: self.dLen = i j = (self.dVal >> (i * 2)) & 3 if j == 0 or j == 1: return if j == 2: if (self.dVal >> ((i + 1) * 2) & 1) != 1: return self.dVal = self.dVal + (1 << (i * 2 + 1)) return if j == 3: temp = 3 << (i * 2) temp = temp ^ -1 self.dVal = self.dVal & temp self.b((i + 1) * 2) i = i + 1 def b(self, pos): if pos == 0: self.inc() return if (self.dVal >> pos) & 1 == 0: self.dVal = self.dVal + (1 << pos) self.a(int(pos / 2)) if pos > 1: self.a(int(pos / 2) - 1) else: temp = 1 << pos temp = temp ^ -1 self.dVal = self.dVal & temp self.b(pos + 1) self.b(pos - (2 if pos > 1 else 1)) def c(self, pos): if (self.dVal >> pos) & 1 == 1: temp = 1 << pos temp = temp ^ -1 self.dVal = self.dVal & temp return self.c(pos + 1) if pos > 0: self.b(pos - 1) else: self.inc() def inc(self): self.dVal = self.dVal + 1 self.a(0) def __add__(self, rhs): copy = self rhs_dVal = rhs.dVal limit = (rhs.dLen + 1) * 2 for gn in range(0, limit): if ((rhs_dVal >> gn) & 1) == 1: copy.b(gn) return copy def __sub__(self, rhs): copy = self rhs_dVal = rhs.dVal limit = (rhs.dLen + 1) * 2 for gn in range(0, limit): if (rhs_dVal >> gn) & 1 == 1: copy.c(gn) while (((copy.dVal >> ((copy.dLen * 2) & 31)) & 3) == 0) or (copy.dLen == 0): copy.dLen = copy.dLen - 1 return copy def __mul__(self, rhs): na = copy.deepcopy(rhs) nb = copy.deepcopy(rhs) nr = Zeckendorf() dVal = self.dVal for i in range(0, (self.dLen + 1) * 2): if ((dVal >> i) & 1) > 0: nr = nr + nb nt = copy.deepcopy(nb) nb = nb + na na = copy.deepcopy(nt) return nr def __str__(self): dig = [, , ] dig1 = [, , ] if self.dVal == 0: return '0' idx = (self.dVal >> ((self.dLen * 2) & 31)) & 3 sb = dig1[idx] i = self.dLen - 1 while i >= 0: idx = (self.dVal >> (i * 2)) & 3 sb = sb + dig[idx] i = i - 1 return sb print g = Zeckendorf() g = g + Zeckendorf() print g g = g + Zeckendorf() print g g = g + Zeckendorf() print g g = g + Zeckendorf() print g g = g + Zeckendorf() print g print print g = Zeckendorf() g = g - Zeckendorf() print g g = Zeckendorf() g = g - Zeckendorf() print g print print g = Zeckendorf() g = g * Zeckendorf() print g g = Zeckendorf() g = g + Zeckendorf() print g
17Zeckendorf arithmetic
3python
g84h
use strict; use warnings; use feature 'say'; use ntheory <is_prime divisor_sum divisors vecsum forcomb lastfor>; sub in_columns { my($columns, $values) = @_; my @v = split ' ', $values; my $width = int(80/$columns); printf "%${width}d"x$columns."\n", @v[$_*$columns .. -1+(1+$_)*$columns] for 0..-1+@v/$columns; print "\n"; } sub is_Zumkeller { my($n) = @_; return 0 if is_prime($n); my @divisors = divisors($n); return 0 unless @divisors > 2 && 0 == @divisors % 2; my $sigma = divisor_sum($n); return 0 unless 0 == $sigma%2 && ($sigma/2) >= $n; if (1 == $n%2) { return 1 } else { my $Z = 0; forcomb { $Z++, lastfor if vecsum(@divisors[@_]) == $sigma/2 } @divisors; return $Z; } } use constant Inf => 1e10; say 'First 220 Zumkeller numbers:'; my $n = 0; my $z; $z .= do { $n < 220 ? (is_Zumkeller($_) and ++$n and "$_ ") : last } for 1 .. Inf; in_columns(20, $z); say 'First 40 odd Zumkeller numbers:'; $n = 0; $z = ''; $z .= do { $n < 40 ? (!!($_%2) and is_Zumkeller($_) and ++$n and "$_ ") : last } for 1 .. Inf; in_columns(10, $z); say 'First 40 odd Zumkeller numbers not divisible by 5:'; $n = 0; $z = ''; $z .= do { $n < 40 ? (!!($_%2 and $_%5) and is_Zumkeller($_) and ++$n and "$_ ") : last } for 1 .. Inf; in_columns(10, $z);
19Zumkeller numbers
2perl
pfb0