code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
package main import ( "fmt" "rcu" "sort" ) var ascPrimesSet = make(map[int]bool)
0Ascending primes
0go
6t3p
local function is_prime(n) if n < 2 then return false end if n % 2 == 0 then return n==2 end if n % 3 == 0 then return n==3 end for f = 5, n^0.5, 6 do if n%f==0 or n%(f+2)==0 then return false end end return true end local function ascending_primes() local digits, candidates, primes = {1,2,3,4,5,6,7,8,9}, {0}, {} for i = 1, #digits do for j = 1, #candidates do local value = candidates[j] * 10 + digits[i] if is_prime(value) then primes[#primes+1] = value end candidates[#candidates+1] = value end end table.sort(primes) return primes end print(table.concat(ascending_primes(), ", "))
0Ascending primes
1lua
cy92
use strict; use warnings; use ntheory qw( is_prime ); print join('', map { sprintf "%10d", $_ } sort { $a <=> $b } grep /./ && is_prime($_), glob join '', map "{$_,}", 1 .. 9) =~ s/.{50}\K/\n/gr;
0Ascending primes
2perl
w1e6
from sympy import isprime def ascending(x=0): for y in range(x*10 + (x%10) + 1, x*10 + 10): yield from ascending(y) yield(y) print(sorted(x for x in ascending() if isprime(x)))
0Ascending primes
3python
xawr
x=("1 2" "3 4") y=(5 6) sum=( "${x[@]}" "${y[@]}" ) for i in "${sum[@]}"; do echo "$i"; done 1 2 3 4 5 6
1Array concatenation
4bash
ak1r
(TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE)); void *array_concat(const void *a, size_t an, const void *b, size_t bn, size_t s) { char *p = malloc(s * (an + bn)); memcpy(p, a, an*s); memcpy(p + an*s, b, bn*s); return p; } const int a[] = { 1, 2, 3, 4, 5 }; const int b[] = { 6, 7, 8, 9, 0 }; int main(void) { unsigned int i; int *c = ARRAY_CONCAT(int, a, 5, b, 5); for(i = 0; i < 10; i++) printf(, c[i]); free(c); return EXIT_SUCCCESS; }
1Array concatenation
5c
wpec
(concat [1 2 3] [4 5 6])
1Array concatenation
6clojure
8x05
package main import "fmt" func main() {
1Array concatenation
0go
c69g
def list = [1, 2, 3] + ["Crosby", "Stills", "Nash", "Young"]
1Array concatenation
7groovy
3dzd
(++) :: [a] -> [a] -> [a]
1Array concatenation
8haskell
pjbt
public static Object[] concat(Object[] arr1, Object[] arr2) { Object[] res = new Object[arr1.length + arr2.length]; System.arraycopy(arr1, 0, res, 0, arr1.length); System.arraycopy(arr2, 0, res, arr1.length, arr2.length); return res; }
1Array concatenation
9java
rug0
var a = [1,2,3], b = [4,5,6], c = a.concat(b);
1Array concatenation
10javascript
b7ki
fun main(args: Array<String>) { val a: Array<Int> = arrayOf(1, 2, 3)
1Array concatenation
11kotlin
v921
a = {1, 2, 3} b = {4, 5, 6} for _, v in pairs(b) do table.insert(a, v) end print(table.concat(a, ", "))
1Array concatenation
1lua
ucvl
my @arr1 = (1, 2, 3); my @arr2 = (4, 5, 6); my @arr3 = (@arr1, @arr2);
1Array concatenation
2perl
0ws4
$arr1 = array(1, 2, 3); $arr2 = array(4, 5, 6); $arr3 = array_merge($arr1, $arr2);
1Array concatenation
12php
5lus
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr4 = arr1 + arr2 assert arr4 == [1, 2, 3, 4, 5, 6] arr4.extend(arr3) assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
1Array concatenation
3python
8x0o
a1 <- c(1, 2, 3) a2 <- c(3, 4, 5) a3 <- c(a1, a2)
1Array concatenation
13r
x1w2
enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 }; char *Lines[MAX_ROWS] = { , , , , , , , , , , , , }; typedef struct { unsigned bit3s; unsigned mask; unsigned data; char A[NAME_SZ+2]; }NAME_T; NAME_T names[MAX_NAMES]; unsigned idx_name; enum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR}; unsigned header[MAX_HDR]; unsigned idx_hdr; int bit_hdr(char *pLine); int bit_names(char *pLine); void dump_names(void); void make_test_hdr(void); int main(void){ char *p1; int rv; printf(); make_test_hdr(); idx_name = 0; for( int i=0; i<MAX_ROWS;i++ ){ p1 = Lines[i]; if( p1==NULL ) break; if( rv = bit_hdr(Lines[i]), rv>0) continue; if( rv = bit_names(Lines[i]),rv>0) continue; } dump_names(); } int bit_hdr(char *pLine){ char *p1 = strchr(pLine,'+'); if( p1==NULL ) return 0; int numbits=0; for( int i=0; i<strlen(p1)-1; i+=3 ){ if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0; numbits++; } return numbits; } int bit_names(char *pLine){ char *p1,*p2 = pLine, tmp[80]; unsigned sz=0, maskbitcount = 15; while(1){ p1 = strchr(p2,'|'); if( p1==NULL ) break; p1++; p2 = strchr(p1,'|'); if( p2==NULL ) break; sz = p2-p1; tmp[sz] = 0; int k=0; for(int j=0; j<sz;j++){ if( p1[j] > ' ') tmp[k++] = p1[j]; } tmp[k]= 0; sz++; NAME_T *pn = &names[idx_name++]; strcpy(&pn->A[0], &tmp[0]); pn->bit3s = sz/3; if( pn->bit3s < 16 ){ for( int i=0; i<pn->bit3s; i++){ pn->mask |= 1 << maskbitcount--; } pn->data = header[idx_hdr] & pn->mask; unsigned m2 = pn->mask; while( (m2 & 1)==0 ){ m2>>=1; pn->data >>= 1; } if( pn->mask == 0xf ) idx_hdr++; } else{ pn->data = header[idx_hdr++]; } } return sz; } void dump_names(void){ NAME_T *pn; printf(); for( int i=0; i<MAX_NAMES; i++ ){ pn = &names[i]; if( pn->bit3s < 1 ) break; printf(,pn->A, pn->bit3s, pn->mask, pn->data); } puts(); } void make_test_hdr(void){ header[ID] = 1024; header[QDCOUNT] = 12; header[ANCOUNT] = 34; header[NSCOUNT] = 56; header[ARCOUNT] = 78; header[BITS] = 0xB50A; }
2ASCII art diagram converter
5c
c39c
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr4 = arr1 + arr2 arr4.concat(arr3)
1Array concatenation
14ruby
isoh
fn main() { let a_vec = vec![1, 2, 3, 4, 5]; let b_vec = vec![6; 5]; let c_vec = concatenate_arrays(&a_vec, &b_vec); println!("{:?} ~ {:?} => {:?}", a_vec, b_vec, c_vec); } fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> { let mut concat = x.to_vec(); concat.extend_from_slice(y); concat }
1Array concatenation
15rust
n0i4
package main import ( "fmt" "log" "math/big" "strings" ) type result struct { name string size int start int end int } func (r result) String() string { return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end) } func validate(diagram string) []string { var lines []string for _, line := range strings.Split(diagram, "\n") { line = strings.Trim(line, " \t") if line != "" { lines = append(lines, line) } } if len(lines) == 0 { log.Fatal("diagram has no non-empty lines!") } width := len(lines[0]) cols := (width - 1) / 3 if cols != 8 && cols != 16 && cols != 32 && cols != 64 { log.Fatal("number of columns should be 8, 16, 32 or 64") } if len(lines)%2 == 0 { log.Fatal("number of non-empty lines should be odd") } if lines[0] != strings.Repeat("+--", cols)+"+" { log.Fatal("incorrect header line") } for i, line := range lines { if i == 0 { continue } else if i%2 == 0 { if line != lines[0] { log.Fatal("incorrect separator line") } } else if len(line) != width { log.Fatal("inconsistent line widths") } else if line[0] != '|' || line[width-1] != '|' { log.Fatal("non-separator lines must begin and end with '|'") } } return lines } func decode(lines []string) []result { fmt.Println("Name Bits Start End") fmt.Println("======= ==== ===== ===") start := 0 width := len(lines[0]) var results []result for i, line := range lines { if i%2 == 0 { continue } line := line[1 : width-1] for _, name := range strings.Split(line, "|") { size := (len(name) + 1) / 3 name = strings.TrimSpace(name) res := result{name, size, start, start + size - 1} results = append(results, res) fmt.Println(res) start += size } } return results } func unpack(results []result, hex string) { fmt.Println("\nTest string in hex:") fmt.Println(hex) fmt.Println("\nTest string in binary:") bin := hex2bin(hex) fmt.Println(bin) fmt.Println("\nUnpacked:\n") fmt.Println("Name Size Bit pattern") fmt.Println("======= ==== ================") for _, res := range results { fmt.Printf("%-7s %2d %s\n", res.name, res.size, bin[res.start:res.end+1]) } } func hex2bin(hex string) string { z := new(big.Int) z.SetString(hex, 16) return fmt.Sprintf("%0*b", 4*len(hex), z) } func main() { const diagram = ` +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ` lines := validate(diagram) fmt.Println("Diagram after trimming whitespace and removal of blank lines:\n") for _, line := range lines { fmt.Println(line) } fmt.Println("\nDecoded:\n") results := decode(lines) hex := "78477bbf5496e12e1bf169a4"
2ASCII art diagram converter
0go
wbeg
val arr1 = Array( 1, 2, 3 ) val arr2 = Array( 4, 5, 6 ) val arr3 = Array( 7, 8, 9 ) arr1 ++ arr2 ++ arr3
1Array concatenation
16scala
tifb
import Text.ParserCombinators.ReadP import Control.Monad (guard) data Field a = Field { fieldName :: String , fieldSize :: Int , fieldValue :: Maybe a} instance Show a => Show (Field a) where show (Field n s a) = case a of Nothing -> n ++ "\t" ++ show s Just x -> n ++ "\t" ++ show s ++ "\t" ++ show x newtype Data a = Data { fields :: [Field a] } instance Show a => Show (Data a) where show (Data fs) = "NAME\tSIZE\tVALUE\n" ++ unlines (show <$> fs) instance Read (Data a) where readsPrec _ = readP_to_S parseData parseData = do n <- parseHeader guard (n `elem` [8,16,32,64]) Data . concat <$> many1 (parseRow n) where parseRow n = do fs <- char '|' *> many parseField <* char '\n' guard $ sum (fieldSize <$> fs) == n m <- parseHeader guard $ m == n return fs parseHeader = do char '+' n <- length <$> many1 (string " char '\n' return n parseField = do s1 <- many (char ' ') f <- munch1 $ not . (`elem` " |") s2 <- many (char ' ') char '|' let n = (length (s1 ++ f ++ s2) + 1) `div` 3 return $ Field f n Nothing readData :: Data a -> [b] -> Data [b] readData d = Data . go (fields d) where go fs [] = (\f -> f {fieldValue = Nothing}) <$> fs go (f:fs) s = let (x, xs) = splitAt (fieldSize f) s in f {fieldValue = Just x}: go fs xs diagram = unlines ["+ ,"| ID |" ,"+ ,"|QR| Opcode |AA|TC|RD|RA| Z | RCODE |" ,"+ ,"| QDCOUNT |" ,"+ ,"| ANCOUNT |" ,"+ ,"| NSCOUNT |" ,"+ ,"| ARCOUNT |" ,"+ dataSample = concat ["011110000100011101111011101111110101010010010110", "111000010010111000011011111100010110100110100100"]
2ASCII art diagram converter
8haskell
6d3k
import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class AsciiArtDiagramConverter { private static final String TEST = "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ID |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| QDCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ANCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| NSCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ARCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"; public static void main(String[] args) { validate(TEST); display(TEST); Map<String,List<Integer>> asciiMap = decode(TEST); displayMap(asciiMap); displayCode(asciiMap, "78477bbf5496e12e1bf169a4"); } private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) { System.out.printf("%nTest string in hex:%n%s%n%n", hex); String bin = new BigInteger(hex,16).toString(2);
2ASCII art diagram converter
9java
nsih
null
2ASCII art diagram converter
10javascript
3nz0
local function validate(diagram) local lines = {} for s in diagram:gmatch("[^\r\n]+") do s = s:match("^%s*(.-)%s*$") if s~="" then lines[#lines+1]=s end end
2ASCII art diagram converter
1lua
0esd
use strict; use warnings; $_ = <<END; +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ END my $template; my @names; while( /\| *(\w+) */g ) { printf "%10s is%2d bits\n", $1, my $length = length($&) / 3; push @names, $1; $template .= "A$length "; } my $input = '78477bbf5496e12e1bf169a4'; my %datastructure; @datastructure{ @names } = unpack $template, unpack 'B*', pack 'H*', $input; print "\ntemplate = $template\n\n"; use Data::Dump 'dd'; dd 'datastructure', \%datastructure;
2ASCII art diagram converter
2perl
u9vr
let array1 = [1,2,3] let array2 = [4,5,6] let array3 = array1 + array2
1Array concatenation
17swift
oq8k
def validate(diagram): rawlines = diagram.splitlines() lines = [] for line in rawlines: if line != '': lines.append(line) if len(lines) == 0: print('diagram has no non-empty lines!') return None width = len(lines[0]) cols = (width - 1) if cols not in [8, 16, 32, 64]: print('number of columns should be 8, 16, 32 or 64') return None if len(lines)%2 == 0: print('number of non-empty lines should be odd') return None if lines[0] != (('+--' * cols)+'+'): print('incorrect header line') return None for i in range(len(lines)): line=lines[i] if i == 0: continue elif i%2 == 0: if line != lines[0]: print('incorrect separator line') return None elif len(line) != width: print('inconsistent line widths') return None elif line[0] != '|' or line[width-1] != '|': print() return None return lines def decode(lines): print() print() startbit = 0 results = [] for line in lines: infield=False for c in line: if not infield and c == '|': infield = True spaces = 0 name = '' elif infield: if c == ' ': spaces += 1 elif c != '|': name += c else: bits = (spaces + len(name) + 1) endbit = startbit + bits - 1 print('{0:7} {1:2d} {2:2d} {3:2d}'.format(name, bits, startbit, endbit)) reslist = [name, bits, startbit, endbit] results.append(reslist) spaces = 0 name = '' startbit += bits return results def unpack(results, hex): print() print(hex) print() bin = f'{int(hex, 16):0>{4*len(hex)}b}' print(bin) print() print() print() for r in results: name = r[0] size = r[1] startbit = r[2] endbit = r[3] bitpattern = bin[startbit:endbit+1] print('{0:7} {1:2d} {2:16}'.format(name, size, bitpattern)) diagram = lines = validate(diagram) if lines == None: print() else: print() print() print() for line in lines: print(line) print() print() print() results = decode(lines) hex = unpack(results, hex)
2ASCII art diagram converter
3python
5cux
header = <<HEADER +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ HEADER Item = Struct.new(:name, :bits, :range) RE = /\| *\w+ */ i = 0 table = header.scan(RE).map{|m| Item.new( m.delete(), b = m.size/3, i...(i += b)) } teststr = padding = table.sum(&:bits) binstr = teststr.hex.to_s(2).rjust(padding, ) table.each{|el| p el.values}; puts table.each{|el| puts % [el.name, el.bits, binstr[el.range] ]}
2ASCII art diagram converter
14ruby
g24q
use std::{borrow::Cow, io::Write}; pub type Bit = bool; #[derive(Clone, Debug)] pub struct Field { name: String, from: usize, to: usize, } impl Field { pub fn new(name: String, from: usize, to: usize) -> Self { assert!(from < to); Self { name, from, to } } pub fn name(&self) -> &str { &self.name } pub fn from(&self) -> usize { self.from } pub fn to(&self) -> usize { self.to } pub fn size(&self) -> usize { self.to - self.from } pub fn extract_bits<'a>( &self, bytes: &'a [u8], ) -> Option<impl Iterator<Item = (usize, Bit)> + 'a> { if self.to <= bytes.len() * 8 { Some((self.from..self.to).map(move |index| { let byte = bytes[index / 8]; let bit_index = 7 - (index% 8); let bit_value = (byte >> bit_index) & 1 == 1; (index, bit_value) })) } else { None } } fn extend(&mut self, new_to: usize) { assert!(self.to <= new_to); self.to = new_to; } } trait Consume: Iterator { fn consume(&mut self, value: Self::Item) -> Result<Self::Item, Option<Self::Item>> where Self::Item: PartialEq, { match self.next() { Some(v) if v == value => Ok(v), Some(v) => Err(Some(v)), None => Err(None), } } } impl<T: Iterator> Consume for T {} #[derive(Clone, Copy, Debug)] enum ParserState { Uninitialized, ExpectBorder, ExpectField, AllowEmpty, } #[derive(Clone, Copy, Debug)] pub enum ParserError { ParsingFailed, UnexpectedEnd, InvalidBorder, WrongLineWidth, FieldExpected, BadField, } #[derive(Debug)] pub(crate) struct Parser { state: Option<ParserState>, width: usize, from: usize, fields: Vec<Field>, } impl Parser { #[allow(clippy::new_without_default)] pub fn new() -> Self { Self { state: Some(ParserState::Uninitialized), width: 0, from: 0, fields: Vec::new(), } } pub fn accept(&mut self, line: &str) -> Result<(), ParserError> { if let Some(state) = self.state.take() { let line = line.trim(); if!line.is_empty() { self.state = Some(match state { ParserState::Uninitialized => self.parse_border(line)?, ParserState::ExpectBorder => self.accept_border(line)?, ParserState::ExpectField => self.parse_fields(line)?, ParserState::AllowEmpty => self.extend_field(line)?, }); } Ok(()) } else { Err(ParserError::ParsingFailed) } } pub fn finish(self) -> Result<Vec<Field>, ParserError> { match self.state { Some(ParserState::ExpectField) => Ok(self.fields), _ => Err(ParserError::UnexpectedEnd), } } fn parse_border(&mut self, line: &str) -> Result<ParserState, ParserError> { self.width = Parser::border_columns(line).map_err(|_| ParserError::InvalidBorder)?; Ok(ParserState::ExpectField) } fn accept_border(&mut self, line: &str) -> Result<ParserState, ParserError> { match Parser::border_columns(line) { Ok(width) if width == self.width => Ok(ParserState::ExpectField), Ok(_) => Err(ParserError::WrongLineWidth), Err(_) => Err(ParserError::InvalidBorder), } } fn parse_fields(&mut self, line: &str) -> Result<ParserState, ParserError> { let mut slots = line.split('|');
2ASCII art diagram converter
15rust
rvg5
fruit=("apple" "orange" "lemon") echo "${
3Array length
4bash
9tms
int main() { const char *fruit[2] = { , }; int length = sizeof(fruit) / sizeof(fruit[0]); printf(, length); return 0; }
3Array length
5c
l3cy
(count ["apple" "orange"]) (alength (into-array ["apple" "orange"]))
3Array length
6clojure
4c5o
arrLength(arr) { return arr.length; } main() { var fruits = ['apple', 'orange']; print(arrLength(fruits)); }
3Array length
18dart
3izz
package main import "fmt" func main() { arr := [...]string{"apple", "orange", "pear"} fmt.Printf("Length of%v is%v.\n", arr, len(arr)) }
3Array length
0go
xbwf
def fruits = ['apple','orange'] println fruits.size()
3Array length
7groovy
prbo
length ["apple", "orange"]
3Array length
8haskell
yd66
public class ArrayLength { public static void main(String[] args) { System.out.println(new String[]{"apple", "orange"}.length); } }
3Array length
9java
dsn9
console.log(['apple', 'orange'].length);
3Array length
10javascript
6n38
fun main(args: Array<String>) { println(arrayOf("apple", "orange").size) }
3Array length
11kotlin
0asf
null
3Array length
1lua
8e0e
my @array = qw "apple orange banana", 4, 42; scalar @array; 0 + @arrray; '' . @array; my $elems = @array; scalar @{ [1,2,3] }; my $array_ref = \@array; scalar @$array_ref; sub takes_a_scalar ($) { my ($a) = @_; return $a } takes_a_scalar @array;
3Array length
2perl
59u2
print count(['apple', 'orange']);
3Array length
12php
ow85
int main(int argc, char *argv[]) { int a, b; if (argc < 3) exit(1); b = atoi(argv[--argc]); if (b == 0) exit(2); a = atoi(argv[--argc]); printf(, a+b); printf(, a-b); printf(, a*b); printf(, a/b); printf(, a%b); return 0; }
4Arithmetic/Integer
5c
z8tx
(defn myfunc [] (println "Enter x and y") (let [x (read), y (read)] (doseq [op '(+ - * / Math/pow rem)] (let [exp (list op x y)] (printf "%s=%s\n" exp (eval exp))))))
4Arithmetic/Integer
6clojure
9fma
>>> print(len(['apple', 'orange'])) 2 >>>
3Array length
3python
4c5k
a <- c('apple','orange') length(a)
3Array length
13r
26lg
puts ['apple', 'orange'].length
3Array length
14ruby
r2gs
fn main() { let array = ["foo", "bar", "baz", "biff"]; println!("the array has {} elements", array.len()); }
3Array length
15rust
7vrc
println(Array("apple", "orange").length)
3Array length
16scala
k4hk
SELECT COUNT() FROM (VALUES ('apple'),('orange'));
3Array length
19sql
17pg
let fruits = ["apple", "orange"]
3Array length
17swift
gl49
package main import "fmt" func main() { var a, b int fmt.Print("enter two integers: ") fmt.Scanln(&a, &b) fmt.Printf("%d +%d =%d\n", a, b, a+b) fmt.Printf("%d -%d =%d\n", a, b, a-b) fmt.Printf("%d *%d =%d\n", a, b, a*b) fmt.Printf("%d /%d =%d\n", a, b, a/b)
4Arithmetic/Integer
0go
k5hz
def arithmetic = { a, b -> println """ a + b = ${a} + ${b} = ${a + b} a - b = ${a} - ${b} = ${a - b} a * b = ${a} * ${b} = ${a * b} a / b = ${a} / ${b} = ${a / b} !!! Converts to floating point! (int)(a / b) = (int)(${a} / ${b}) = ${(int)(a / b)} !!! Truncates downward after the fact a.intdiv(b) = ${a}.intdiv(${b}) = ${a.intdiv(b)} !!! Behaves as if truncating downward, actual implementation varies a% b = ${a}% ${b} = ${a% b} Exponentiation is also a base arithmetic operation in Groovy, so: a ** b = ${a} ** ${b} = ${a ** b} """ }
4Arithmetic/Integer
7groovy
gc46
main = do a <- readLn :: IO Integer b <- readLn :: IO Integer putStrLn $ "a + b = " ++ show (a + b) putStrLn $ "a - b = " ++ show (a - b) putStrLn $ "a * b = " ++ show (a * b) putStrLn $ "a to the power of b = " ++ show (a ** b) putStrLn $ "a to the power of b = " ++ show (a ^ b) putStrLn $ "a to the power of b = " ++ show (a ^^ b) putStrLn $ "a `div` b = " ++ show (a `div` b) putStrLn $ "a `mod` b = " ++ show (a `mod` b) putStrLn $ "a `divMod` b = " ++ show (a `divMod` b) putStrLn $ "a `quot` b = " ++ show (a `quot` b) putStrLn $ "a `rem` b = " ++ show (a `rem` b) putStrLn $ "a `quotRem` b = " ++ show (a `quotRem` b)
4Arithmetic/Integer
8haskell
nxie
import java.util.Scanner; public class IntegerArithmetic { public static void main(String[] args) {
4Arithmetic/Integer
9java
qbxa
var a = parseInt(get_input("Enter an integer"), 10); var b = parseInt(get_input("Enter an integer"), 10); WScript.Echo("a = " + a); WScript.Echo("b = " + b); WScript.Echo("sum: a + b = " + (a + b)); WScript.Echo("difference: a - b = " + (a - b)); WScript.Echo("product: a * b = " + (a * b)); WScript.Echo("quotient: a / b = " + (a / b | 0));
4Arithmetic/Integer
10javascript
iwol
void divisor_count_and_sum(unsigned int n, unsigned int* pcount, unsigned int* psum) { unsigned int divisor_count = 1; unsigned int divisor_sum = 1; unsigned int power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) { ++divisor_count; divisor_sum += power; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1, sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { ++count; sum += power; } divisor_count *= count; divisor_sum *= sum; } if (n > 1) { divisor_count *= 2; divisor_sum *= n + 1; } *pcount = divisor_count; *psum = divisor_sum; } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, &divisor_count, &divisor_sum); if (divisor_sum % divisor_count != 0) continue; ++arithmetic_count; if (divisor_count > 2) ++composite_count; if (arithmetic_count <= 100) { printf(, n); if (arithmetic_count % 10 == 0) printf(); } if (arithmetic_count == 1000 || arithmetic_count == 10000 || arithmetic_count == 100000 || arithmetic_count == 1000000) { printf(, arithmetic_count, n); printf(, n, composite_count); } } return 0; }
5Arithmetic numbers
5c
6o32
null
4Arithmetic/Integer
11kotlin
1rpd
package main import ( "fmt" "math" "rcu" "sort" ) func main() { arithmetic := []int{1} primes := []int{} limit := int(1e6) for n := 3; len(arithmetic) < limit; n++ { divs := rcu.Divisors(n) if len(divs) == 2 { primes = append(primes, n) arithmetic = append(arithmetic, n) } else { mean := float64(rcu.SumInts(divs)) / float64(len(divs)) if mean == math.Trunc(mean) { arithmetic = append(arithmetic, n) } } } fmt.Println("The first 100 arithmetic numbers are:") rcu.PrintTable(arithmetic[0:100], 10, 3, false) for _, x := range []int{1e3, 1e4, 1e5, 1e6} { last := arithmetic[x-1] lastc := rcu.Commatize(last) fmt.Printf("\nThe%sth arithmetic number is:%s\n", rcu.Commatize(x), lastc) pcount := sort.SearchInts(primes, last) + 1 if !rcu.IsPrime(last) { pcount-- } comp := x - pcount - 1
5Arithmetic numbers
0go
p4bg
use strict; use warnings; use feature 'say'; use List::Util <max sum>; use ntheory <is_prime divisors>; use Lingua::EN::Numbers qw(num2en num2en_ordinal); sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub table { my $t = 10 * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr } my @A = 0; for my $n (1..2E6) { my @div = divisors $n; push @A, $n if 0 == sum(@div) % @div; } say "The first @{[num2en 100]} arithmetic numbers:"; say table @A[1..100]; for my $x (1E3, 1E4, 1E5, 1E6) { say "\nThe @{[num2en_ordinal $x]}: " . comma($A[$x]) . "\nComposite arithmetic numbers @{[comma $A[$x]]}: " . comma -1 + grep { not is_prime($_) } @A[1..$x]; }
5Arithmetic numbers
2perl
cf9a
def factors(n: int): f = set([1, n]) i = 2 while True: j = n if j < i: break if i * j == n: f.add(i) f.add(j) i += 1 return f arithmetic_count = 0 composite_count = 0 n = 1 while arithmetic_count <= 1000000: f = factors(n) if (sum(f)/len(f)).is_integer(): arithmetic_count += 1 if len(f) > 2: composite_count += 1 if arithmetic_count <= 100: print(f'{n:3d} ', end='') if arithmetic_count% 10 == 0: print() if arithmetic_count in (1000, 10000, 100000, 1000000): print(f'\n{arithmetic_count}th arithmetic number is {n}') print(f'Number of composite arithmetic numbers <= {n}: {composite_count}') n += 1
5Arithmetic numbers
3python
ltcv
fn divisor_count_and_sum(mut n: u32) -> (u32, u32) { let mut divisor_count = 1; let mut divisor_sum = 1; let mut power = 2; while (n & 1) == 0 { divisor_count += 1; divisor_sum += power; power <<= 1; n >>= 1; } let mut p = 3; while p * p <= n { let mut count = 1; let mut sum = 1; power = p; while n% p == 0 { count += 1; sum += power; power *= p; n /= p; } divisor_count *= count; divisor_sum *= sum; p += 2; } if n > 1 { divisor_count *= 2; divisor_sum *= n + 1; } (divisor_count, divisor_sum) } fn main() { let mut arithmetic_count = 0; let mut composite_count = 0; let mut n = 1; while arithmetic_count <= 1000000 { let (divisor_count, divisor_sum) = divisor_count_and_sum(n); if divisor_sum% divisor_count!= 0 { n += 1; continue; } arithmetic_count += 1; if divisor_count > 2 { composite_count += 1; } if arithmetic_count <= 100 { print!("{:3} ", n); if arithmetic_count% 10 == 0 { println!(); } } if arithmetic_count == 1000 || arithmetic_count == 10000 || arithmetic_count == 100000 || arithmetic_count == 1000000 { println!("\n{}th arithmetic number is {}", arithmetic_count, n); println!( "Number of composite arithmetic numbers <= {}: {}", n, composite_count ); } n += 1; } }
5Arithmetic numbers
15rust
u6vj
local x = io.read() local y = io.read() print ("Sum: " , (x + y)) print ("Difference: ", (x - y)) print ("Product: " , (x * y)) print ("Quotient: " , (x / y))
4Arithmetic/Integer
1lua
a71v
my $a = <>; my $b = <>; print "sum: ", $a + $b, "\n", "difference: ", $a - $b, "\n", "product: ", $a * $b, "\n", "integer quotient: ", int($a / $b), "\n", "remainder: ", $a % $b, "\n", "exponent: ", $a ** $b, "\n" ;
4Arithmetic/Integer
2perl
mdyz
<?php $a = fgets(STDIN); $b = fgets(STDIN); echo , $a + $b, , , $a - $b, , , $a * $b, , , (int)($a / $b), , , floor($a / $b), , , $a % $b, , , $a ** $b, ; ?>
4Arithmetic/Integer
12php
eja9
x = int(raw_input()) y = int(raw_input()) print % (x + y) print % (x - y) print % (x * y) print % (x / y) print % (x% y) print % divmod(x, y) print % x**y raw_input( )
4Arithmetic/Integer
3python
9fmf
cat("insert number ") a <- scan(nmax=1, quiet=TRUE) cat("insert number ") b <- scan(nmax=1, quiet=TRUE) print(paste('a+b=', a+b)) print(paste('a-b=', a-b)) print(paste('a*b=', a*b)) print(paste('a%/%b=', a%/%b)) print(paste('a%%b=', a%%b)) print(paste('a^b=', a^b))
4Arithmetic/Integer
13r
3ozt
void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) { mpf_add (out1, in1, in2); mpf_div_ui (out1, out1, 2); mpf_mul (out2, in1, in2); mpf_sqrt (out2, out2); } int main (void) { mpf_set_default_prec (300000); mpf_t x0, y0, resA, resB, Z, var; mpf_init_set_ui (x0, 1); mpf_init_set_d (y0, 0.5); mpf_sqrt (y0, y0); mpf_init (resA); mpf_init (resB); mpf_init_set_d (Z, 0.25); mpf_init (var); int n = 1; int i; for(i=0; i<8; i++){ agm(x0, y0, resA, resB); mpf_sub(var, resA, x0); mpf_mul(var, var, var); mpf_mul_ui(var, var, n); mpf_sub(Z, Z, var); n += n; agm(resA, resB, x0, y0); mpf_sub(var, x0, resA); mpf_mul(var, var, var); mpf_mul_ui(var, var, n); mpf_sub(Z, Z, var); n += n; } mpf_mul(x0, x0, x0); mpf_div(x0, x0, Z); gmp_printf (, x0); return 0; }
6Arithmetic-geometric mean/Calculate Pi
5c
lfcy
puts 'Enter x and y' x = gets.to_i y = gets.to_i puts , , , , , ,
4Arithmetic/Integer
14ruby
lzcl
(ns async-example.core (:use [criterium.core]) (:gen-class)) (import '(org.apfloat Apfloat ApfloatMath)) (def precision 8192) (def one (Apfloat. 1M precision)) (def two (Apfloat. 2M precision)) (def four (Apfloat. 4M precision)) (def half (Apfloat. 0.5M precision)) (def quarter (Apfloat. 0.25M precision)) (def isqrt2 (.divide one (ApfloatMath/pow two half))) (defn compute-pi [iterations] (loop [i 0, n one, [a g] [one isqrt2], z quarter] (if (> i iterations) (.divide (.multiply a a) z) (let [x [(.multiply (.add a g) half) (ApfloatMath/pow (.multiply a g) half)] v (.subtract (first x) a)] (recur (inc i) (.add n n) x (.subtract z (.multiply (.multiply v v) n))))))) (doseq [q (partition-all 200 (str (compute-pi 18)))] (println (apply str q)))
6Arithmetic-geometric mean/Calculate Pi
6clojure
4y5o
use std::env; fn main() { let args: Vec<_> = env::args().collect(); let a = args[1].parse::<i32>().unwrap(); let b = args[2].parse::<i32>().unwrap(); println!("sum: {}", a + b); println!("difference: {}", a - b); println!("product: {}", a * b); println!("integer quotient: {}", a / b);
4Arithmetic/Integer
15rust
23lt
val a = Console.readInt val b = Console.readInt val sum = a + b
4Arithmetic/Integer
16scala
5mut
package main import ( "fmt" "math/big" ) func main() { one := big.NewFloat(1) two := big.NewFloat(2) four := big.NewFloat(4) prec := uint(768)
6Arithmetic-geometric mean/Calculate Pi
0go
xjwf
import java.math.MathContext class CalculatePi { private static final MathContext con1024 = new MathContext(1024) private static final BigDecimal bigTwo = new BigDecimal(2) private static final BigDecimal bigFour = new BigDecimal(4) private static BigDecimal bigSqrt(BigDecimal bd, MathContext con) { BigDecimal x0 = BigDecimal.ZERO BigDecimal x1 = BigDecimal.valueOf(Math.sqrt(bd.doubleValue())) while (!Objects.equals(x0, x1)) { x0 = x1 x1 = (bd.divide(x0, con) + x0).divide(bigTwo, con) } return x1 } static void main(String[] args) { BigDecimal a = BigDecimal.ONE BigDecimal g = a.divide(bigSqrt(bigTwo, con1024), con1024) BigDecimal t BigDecimal sum = BigDecimal.ZERO BigDecimal pow = bigTwo while (!Objects.equals(a, g)) { t = (a + g).divide(bigTwo, con1024) g = bigSqrt(a * g, con1024) a = t pow = pow * bigTwo sum = sum + (a * a - g * g) * pow } BigDecimal pi = (bigFour * (a * a)).divide(BigDecimal.ONE - sum, con1024) System.out.println(pi) } }
6Arithmetic-geometric mean/Calculate Pi
7groovy
p5bo
import Prelude hiding (pi) import Data.Number.MPFR hiding (sqrt, pi, div) import Data.Number.MPFR.Instances.Near () digitBits :: (Integral a, Num a) => a -> a digitBits n = (n + 1) `div` 2 * 8 pi :: Integer -> MPFR pi digits = let eps = fromString ("1e-" ++ show digits) (fromInteger $ digitBits digits) 0 two = fromInt Near (getPrec eps) 2 twoi = 2 :: Int twoI = 2 :: Integer pis a g s n = let aB = (a + g) / two gB = sqrt (a * g) aB2 = aB ^^ twoi sB = s + (two ^^ n) * (aB2 - gB ^^ twoi) num = 4 * aB2 den = 1 - sB in (num / den): pis aB gB sB (n + 1) puntil f (a:b:xs) = if f a b then b else puntil f (b:xs) in puntil (\a b -> abs (a - b) < eps) $ pis one (one / sqrt two) zero twoI main :: IO () main = do putStrLn $ toString 1000 $ pi 1000
6Arithmetic-geometric mean/Calculate Pi
8haskell
yo66
null
7Arena storage pool
5c
79rg
import java.math.BigDecimal; import java.math.MathContext; import java.util.Objects; public class Calculate_Pi { private static final MathContext con1024 = new MathContext(1024); private static final BigDecimal bigTwo = new BigDecimal(2); private static final BigDecimal bigFour = new BigDecimal(4); private static BigDecimal bigSqrt(BigDecimal bd, MathContext con) { BigDecimal x0 = BigDecimal.ZERO; BigDecimal x1 = BigDecimal.valueOf(Math.sqrt(bd.doubleValue())); while (!Objects.equals(x0, x1)) { x0 = x1; x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con); } return x1; } public static void main(String[] args) { BigDecimal a = BigDecimal.ONE; BigDecimal g = a.divide(bigSqrt(bigTwo, con1024), con1024); BigDecimal t; BigDecimal sum = BigDecimal.ZERO; BigDecimal pow = bigTwo; while (!Objects.equals(a, g)) { t = a.add(g).divide(bigTwo, con1024); g = bigSqrt(a.multiply(g), con1024); a = t; pow = pow.multiply(bigTwo); sum = sum.add(a.multiply(a).subtract(g.multiply(g)).multiply(pow)); } BigDecimal pi = bigFour.multiply(a.multiply(a)).divide(BigDecimal.ONE.subtract(sum), con1024); System.out.println(pi); } }
6Arithmetic-geometric mean/Calculate Pi
9java
dwn9
-- test.sql -- Tested in SQL*plus DROP TABLE test; CREATE TABLE test (a INTEGER, b INTEGER); INSERT INTO test VALUES ('&&A','&&B'); commit; SELECT a-b difference FROM test; SELECT a*b product FROM test; SELECT trunc(a/b) integer_quotient FROM test; SELECT MOD(a,b) remainder FROM test; SELECT POWER(a,b) exponentiation FROM test;
4Arithmetic/Integer
19sql
rlgp
import java.math.BigDecimal import java.math.MathContext val con1024 = MathContext(1024) val bigTwo = BigDecimal(2) val bigFour = bigTwo * bigTwo fun bigSqrt(bd: BigDecimal, con: MathContext): BigDecimal { var x0 = BigDecimal.ZERO var x1 = BigDecimal.valueOf(Math.sqrt(bd.toDouble())) while (x0 != x1) { x0 = x1 x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con) } return x1 } fun main(args: Array<String>) { var a = BigDecimal.ONE var g = a.divide(bigSqrt(bigTwo, con1024), con1024) var t : BigDecimal var sum = BigDecimal.ZERO var pow = bigTwo while (a != g) { t = (a + g).divide(bigTwo, con1024) g = bigSqrt(a * g, con1024) a = t pow *= bigTwo sum += (a * a - g * g) * pow } val pi = (bigFour * a * a).divide(BigDecimal.ONE - sum, con1024) println(pi) }
6Arithmetic-geometric mean/Calculate Pi
11kotlin
0bsf
typedef long long int fr_int_t; typedef struct { fr_int_t num, den; } frac; fr_int_t gcd(fr_int_t m, fr_int_t n) { fr_int_t t; while (n) { t = n; n = m % n; m = t; } return m; } frac frac_new(fr_int_t num, fr_int_t den) { frac a; if (!den) { printf(FMTFMT, num, den); abort(); } int g = gcd(num, den); if (g) { num /= g; den /= g; } else { num = 0; den = 1; } if (den < 0) { den = -den; num = -num; } a.num = num; a.den = den; return a; } BINOP(add, a.num * b.den + b.num * a.den, a.den * b.den); BINOP(sub, a.num * b.den - b.num + a.den, a.den * b.den); BINOP(mul, a.num * b.num, a.den * b.den); BINOP(div, a.num * b.den, a.den * b.num); int frac_cmp(frac a, frac b) { int l = a.num * b.den, r = a.den * b.num; return l < r ? -1 : l > r; } int frtoi(frac a) { return a.den / a.num; } double frtod(frac a) { return (double)a.den / a.num; } int main() { int n, k; frac sum, kf; for (n = 2; n < 1<<19; n++) { sum = frac_new(1, n); for (k = 2; k * k < n; k++) { if (n % k) continue; kf = frac_new(1, k); sum = frac_add(sum, kf); kf = frac_new(1, n / k); sum = frac_add(sum, kf); } if (frac_cmp_int(sum, 1) == 0) printf(, n); } return 0; }
8Arithmetic/Rational
5c
fed3
void cprint(double complex c) { printf(, creal(c), cimag(c)); } void complex_operations() { double complex a = 1.0 + 1.0I; double complex b = 3.14159 + 1.2I; double complex c; printf(); cprint(a); printf(); cprint(b); c = a + b; printf(); cprint(c); c = a * b; printf(); cprint(c); c = 1.0 / a; printf(); cprint(c); c = -a; printf(); cprint(c); c = conj(a); printf(); cprint(c); printf(); }
9Arithmetic/Complex
5c
0jst
package main import ( "fmt" "runtime" "sync" )
7Arena storage pool
0go
dene
let a = 6 let b = 4 print("sum =\(a+b)") print("difference = \(a-b)") print("product = \(a*b)") print("Integer quotient = \(a/b)") print("Remainder = (a%b)") print("No operator for Exponential")
4Arithmetic/Integer
17swift
ct9t
null
7Arena storage pool
11kotlin
zqts
pool = {}
7Arena storage pool
1lua
3szo
double agm( double a, double g ) { double iota = 1.0E-16; double a1, g1; if( a*g < 0.0 ) { printf( ); exit(1); } while( fabs(a-g)>iota ) { a1 = (a + g) / 2.0; g1 = sqrt(a * g); a = a1; g = g1; } return a; } int main( void ) { double x, y; printf( ); scanf( , &x, &y ); printf( , agm(x, y) ); return 0; }
10Arithmetic-geometric mean
5c
dpnv
use Math::BigFloat try => "GMP,Pari"; my $digits = shift || 100; print agm_pi($digits), "\n"; sub agm_pi { my $digits = shift; my $acc = $digits + 8; my $HALF = Math::BigFloat->new("0.5"); my ($an, $bn, $tn, $pn) = (Math::BigFloat->bone, $HALF->copy->bsqrt($acc), $HALF->copy->bmul($HALF), Math::BigFloat->bone); while ($pn < $acc) { my $prev_an = $an->copy; $an->badd($bn)->bmul($HALF, $acc); $bn->bmul($prev_an)->bsqrt($acc); $prev_an->bsub($an); $tn->bsub($pn * $prev_an * $prev_an); $pn->badd($pn); } $an->badd($bn); $an->bmul($an,$acc)->bdiv(4*$tn, $digits); return $an; }
6Arithmetic-geometric mean/Calculate Pi
2perl
56u2
user> 22/7 22/7 user> 34/2 17 user> (+ 37/5 42/9) 181/15
8Arithmetic/Rational
6clojure
y06b
(ns rosettacode.arithmetic.cmplx (:require [clojure.algo.generic.arithmetic:as ga]) (:import [java.lang Number])) (defrecord Complex [^Number r ^Number i] Object (toString [{:keys [r i]}] (apply str (cond (zero? r) [(if (= i 1) "" i) "i"] (zero? i) [r] :else [r (if (neg? i) "-" "+") i "i"])))) (defmethod ga/+ [Complex Complex] [x y] (map->Complex (merge-with + x y))) (defmethod ga/+ [Complex Number] [{:keys [r i]} y] (->Complex (+ r y) i)) (defmethod ga/- Complex [x] (->> x vals (map -) (apply ->Complex))) (defmethod ga/* [Complex Complex] [x y] (map->Complex (merge-with * x y))) (defmethod ga/* [Complex Number] [{:keys [r i]} y] (->Complex (* r y) (* i y))) (ga/defmethod* ga / Complex [x] (->> x vals (map /) (apply ->Complex))) (defn conj [^Complex {:keys [r i]}] (->Complex r (- i))) (defn inv [^Complex {:keys [r i]}] (let [m (+ (* r r) (* i i))] (->Complex (/ r m) (- (/ i m)))))
9Arithmetic/Complex
6clojure
d1nb
(ns agmcompute (:gen-class)) (import '(org.apfloat Apfloat ApfloatMath)) (def precision 70) (def one (Apfloat. 1M precision)) (def two (Apfloat. 2M precision)) (def half (Apfloat. 0.5M precision)) (def isqrt2 (.divide one (ApfloatMath/pow two half))) (def TOLERANCE (Apfloat. 0.000000M precision)) (defn agm [a g] " Simple AGM Loop calculation " (let [THRESH 1e-65 MAX-LOOPS 1000000] (loop [[an gn] [a g], cnt 0] (if (or (< (ApfloatMath/abs (.subtract an gn)) THRESH) (> cnt MAX-LOOPS)) an (recur [(.multiply (.add an gn) half) (ApfloatMath/pow (.multiply an gn) half)] (inc cnt)))))) (println (agm one isqrt2))
10Arithmetic-geometric mean
6clojure
6x3q
from decimal import * D = Decimal getcontext().prec = 100 a = n = D(1) g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5) for i in range(18): x = [(a + g) * half, (a * g).sqrt()] var = x[0] - a z -= var * var * n n += n a, g = x print(a * a / z)
6Arithmetic-geometric mean/Calculate Pi
3python
4y5k
(malloc 1000 'raw) ; raw allocation, bypass the GC, requires free()-ing (malloc 1000 'uncollectable) ; no GC, for use with other GCs that Racket can be configured with (malloc 1000 'atomic) ; a block of memory without internal pointers (malloc 1000 'nonatomic) ; a block of pointers (malloc 1000 'eternal) ; uncollectable & atomic, similar to raw malloc but no freeing (malloc 1000 'stubborn) ; can be declared immutable when mutation is done (malloc 1000 'interior) ; allocate an immovable block with possible pointers into it (malloc 1000 'atomic-interior); same for atomic chunks (malloc-immobile-cell v) ; allocates a single cell that the GC will not move
7Arena storage pool
3python
pubm
library(Rmpfr) agm <- function(n, prec) { s <- mpfr(0, prec) a <- mpfr(1, prec) g <- sqrt(mpfr("0.5", prec)) p <- as.bigz(4) for (i in seq(n)) { m <- (a + g) / 2L g <- sqrt(a * g) a <- m s <- s + p * (a * a - g * g) p <- p + p } 4L * a * a / (1L - s) } 1e6 * log(10) / log(2) p <- 3322000 x <- agm(20, p) roundMpfr(x - Const("pi", p), 64) f <- file("pi.txt", "w") writeLines(formatMpfr(x, 1e6), f) close(f)
6Arithmetic-geometric mean/Calculate Pi
13r
2tlg
#![feature(rustc_private)] extern crate arena; use arena::TypedArena; fn main() {
7Arena storage pool
15rust
egaj
package require Tcl 8.6 oo::class create Pool { superclass oo::class variable capacity pool busy unexport create constructor args { next {*}$args set capacity 100 set pool [set busy {}] } method new {args} { if {[llength $pool]} { set pool [lassign $pool obj] } else { if {[llength $busy] >= $capacity} { throw {POOL CAPACITY} "exceeded capacity: $capacity" } set obj [next] set newobj [namespace current]::[namespace tail $obj] rename $obj $newobj set obj $newobj } try { [info object namespace $obj]::my Init {*}$args } on error {msg opt} { lappend pool $obj return -options $opt $msg } lappend busy $obj return $obj } method ReturnToPool obj { try { if {"Finalize" in [info object methods $obj -all -private]} { [info object namespace $obj]::my Finalize } } on error {msg opt} { after 0 [list return -options $opt $msg] return false } set idx [lsearch -exact $busy $obj] set busy [lreplace $busy $idx $idx] if {[llength $pool] + [llength $busy] + 1 <= $capacity} { lappend pool $obj return true } else { return false } } method capacity {{value {}}} { if {[llength [info level 0]] == 3} { if {$value < $capacity} { while {[llength $pool] > 0 && [llength $pool] + [llength $busy] > $value} { set pool [lassign $pool obj] rename $obj {} } } set capacity [expr {$value >> 0}] } else { return $capacity } } method clearPool {} { foreach obj $busy { $obj destroy } } method destroy {} { my clearPool next } self method create {class {definition {}}} { set cls [next $class $definition] oo::define $cls method destroy {} { if {![[info object namespace [self class]]::my ReturnToPool [self]]} { next } } return $cls } }
7Arena storage pool
16scala
qjxw
require 'flt' Flt::BinNum.Context.precision = 8192 a = n = 1 g = 1 / Flt::BinNum(2).sqrt z = 0.25 (0..17).each{ x = [(a + g) * 0.5, (a * g).sqrt] var = x[0] - a z -= var * var * n n += n a = x[0] g = x[1] } puts a * a / z
6Arithmetic-geometric mean/Calculate Pi
14ruby
r9gs
null
6Arithmetic-geometric mean/Calculate Pi
15rust
7crc