code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
use strict; use warnings; use feature 'say'; use ntheory 'divisors'; my(@x,$n); do { push(@x,$n) unless $n % scalar(divisors(++$n)) } until 100 == @x; say "Tau numbers - first 100:\n" . ((sprintf "@{['%5d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr);
145Tau number
2perl
0aps4
tau :: Integral a => a -> a tau n | n <= 0 = error "Not a positive integer" tau n = go 0 (1, 1) where yo i = (i, i * i) go r (i, ii) | n < ii = r | n == ii = r + 1 | 0 == mod n i = go (r + 2) (yo $ i + 1) | otherwise = go r (yo $ i + 1) main = print $ map tau [1..100]
147Tau function
8haskell
yd866
os.execute( "clear" )
151Terminal control/Clear the screen
1lua
3iezo
null
138Ternary logic
11kotlin
rvrgo
from colorama import init, Fore, Back, Style init(autoreset=True) print Fore.RED + print Back.BLUE + Fore.YELLOW + print % (Style.BRIGHT, Style.NORMAL) print Fore.YELLOW + print Fore.CYAN + print Fore.GREEN + print Fore.MAGENTA + print Back.YELLOW + Fore.BLUE + Style.BRIGHT + * 40 +
142Terminal control/Coloured text
3python
mftyh
typedef struct { double x, y; } vec_t, *vec; inline double dot(vec a, vec b) { return a->x * b->x + a->y * b->y; } inline double cross(vec a, vec b) { return a->x * b->y - a->y * b->x; } inline vec vsub(vec a, vec b, vec res) { res->x = a->x - b->x; res->y = a->y - b->y; return res; } int left_of(vec a, vec b...
154Sutherland-Hodgman polygon clipping
5c
dsjnv
package main import ( "fmt" "math/big" ) func main() { one := big.NewInt(1) two := big.NewInt(2) next := new(big.Int) sylvester := []*big.Int{two} prod := new(big.Int).Set(two) count := 1 for count < 10 { next.Add(prod, one) sylvester = append(sylvester, new(big.Int...
155Sylvester's sequence
0go
9temt
sylvester :: [Integer] sylvester = map s [0 ..] where s 0 = 2 s n = succ $ foldr ((*) . s) 1 [0 .. pred n] main :: IO () main = do putStrLn "First 10 elements of Sylvester's sequence:" putStr $ unlines $ map show $ take 10 sylvester putStr "\nSum of reciprocals by sum over map: " print $ sum $ map (...
155Sylvester's sequence
8haskell
bg3k2
use std::collections::BTreeSet; use std::collections::HashSet; use std::fs::File; use std::io::{self, BufRead}; use std::iter::FromIterator; fn load_dictionary(filename: &str) -> std::io::Result<BTreeSet<String>> { let file = File::open(filename)?; let mut dict = BTreeSet::new(); for line in io::BufReader:...
143Teacup rim text
15rust
juu72
import Foundation func loadDictionary(_ path: String) throws -> Set<String> { let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii) return Set<String>(contents.components(separatedBy: "\n").filter{!$0.isEmpty}) } func rotate<T>(_ array: inout [T]) { guard array.count > 1 else { ...
143Teacup rim text
17swift
r22gg
public class TauFunction { private static long divisorCount(long n) { long total = 1;
147Tau function
9java
dsen9
enum class Day { first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth; val header = "On the " + this + " day of Christmas, my true love sent to me\n\t" } fun main(x: Array<String>) { val gifts = listOf("A partridge in a pear tree", "Two turtle ...
139The Twelve Days of Christmas
11kotlin
4cu57
(defn super [d] (let [run (apply str (repeat d (str d)))] (filter #(clojure.string/includes? (str (* d (Math/pow % d ))) run) (range)))) (doseq [d (range 2 9)] (println (str d ": ") (take 10 (super d))))
153Super-d numbers
6clojure
dshnb
int main(){ double a,b,n,i,incr = 0.0001; printf(); scanf(,&a,&b); printf(); scanf(,&n); initwindow(500,500,); for(i=0;i<2*pi;i+=incr){ putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15); } printf(,i); getch(); closegraph(); }
156Superellipse
5c
xbcwu
import java.util.PriorityQueue; import java.util.ArrayList; import java.util.List; import java.util.Iterator; class CubeSum implements Comparable<CubeSum> { public long x, y, value; public CubeSum(long x, long y) { this.x = x; this.y = y; this.value = x*x*x + y*y*y; } public String toString() { return St...
144Taxicab numbers
9java
umyvv
package main import "fmt" const max = 12 var ( super []byte pos int cnt [max]int )
152Superpermutation minimisation
0go
ju37d
def tau(n): assert(isinstance(n, int) and 0 < n) ans, i, j = 0, 1, 1 while i*i <= n: if 0 == n%i: ans += 1 j = n if j != i: ans += 1 i += 1 return ans def is_tau_number(n): assert(isinstance(n, int)) if n <= 0: return F...
145Tau number
3python
8e10o
function divisorCount(n) local total = 1
147Tau function
1lua
8eb0e
require 'rubygems' require 'colored' print 'Colors are'.bold print ' black'.black print ' blue'.blue print ' cyan'.cyan print ' green'.green print ' magenta'.magenta print ' red'.red print ' white '.white print 'and'.underline, ' yellow'.yellow, puts 'black on blue'.black_on_blue puts 'black on cyan'.black_on_cyan pu...
142Terminal control/Coloured text
14ruby
cz39k
use strict; use warnings; use feature 'say'; use List::Util 'reduce'; use Math::AnyNum ':overload'; local $Math::AnyNum::PREC = 845; my(@S,$sum); push @S, 1 + reduce { $a * $b } @S for 0..10; shift @S; $sum += 1/$_ for @S; say "First 10 elements of Sylvester's sequence: @S"; say "\nSum of the reciprocals of first 10 ...
155Sylvester's sequence
2perl
s1vq3
var n3s = [], s3s = {} for (var n = 1, e = 1200; n < e; n += 1) n3s[n] = n * n * n for (var a = 1; a < e - 1; a += 1) { var a3 = n3s[a] for (var b = a; b < e; b += 1) { var b3 = n3s[b] var s3 = a3 + b3, abs = s3s[s3] if (!abs) s3s[s3] = abs = [] abs.push([a, b]) ...
144Taxicab numbers
10javascript
7v2rd
import static java.util.stream.IntStream.rangeClosed class Superpermutation { final static int nMax = 12 static char[] superperm static int pos static int[] count = new int[nMax] static int factSum(int n) { return rangeClosed(1, n) .map({ m -> rangeClosed(1, m).reduce(1, { a, ...
152Superpermutation minimisation
7groovy
59nuv
tau <- function(t) { results <- integer(0) resultsCount <- 0 n <- 1 while(resultsCount != t) { condition <- function(n) (n %% length(c(Filter(function(x) n %% x == 0, seq_len(n %/% 2)), n))) == 0 if(condition(n)) { resultsCount <- resultsCount + 1 results[resultsCount] <- n } n...
145Tau number
13r
xbhw2
system('clear')
151Terminal control/Clear the screen
2perl
bg9k4
const ESC: &str = "\x1B["; const RESET: &str = "\x1B[0m"; fn main() { println!("ForegroundBackground--------------------------------------------------------------"); print!(" "); for i in 40..48 { print!(" ESC[{}m ", i); } println!("\n-----------------------------------------------...
142Terminal control/Coloured text
15rust
l36cc
object ColouredText extends App { val ESC = "\u001B" val (normal, bold, blink, black, white) = (ESC + "[0", ESC + "[1" , ESC + "[5"
142Terminal control/Coloured text
16scala
um9v8
require 'pstore' require 'set' Address = Struct.new :id, :street, :city, :state, :zip db = PStore.new() db.transaction do db[:next] ||= 0 db[:ids] ||= Set[] end
148Table creation/Postal addresses
14ruby
l3ncl
package main import ( "fmt" "math/big" "strings" "time" ) func main() { start := time.Now() rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"} one := big.NewInt(1) nine := big.NewInt(9) for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) ...
153Super-d numbers
0go
umovt
import Data.List (isInfixOf) import Data.Char (intToDigit) isSuperd :: (Show a, Integral a) => a -> a -> Bool isSuperd p n = (replicate <*> intToDigit) (fromIntegral p) `isInfixOf` show (p * n ^ p) findSuperd :: (Show a, Integral a) => a -> [a] findSuperd p = filter (isSuperd p) [1 ..] main :: IO () main = mapM_...
153Super-d numbers
8haskell
wk2ed
'''Sylvester's sequence''' from functools import reduce from itertools import count, islice def sylvester(): '''Non-finite stream of the terms of Sylvester's sequence. (OEIS A000058) ''' def go(n): return 1 + reduce( lambda a, x: a * go(x), range(0, n), ...
155Sylvester's sequence
3python
0ausq
import static java.util.stream.IntStream.rangeClosed; public class Test { final static int nMax = 12; static char[] superperm; static int pos; static int[] count = new int[nMax]; static int factSum(int n) { return rangeClosed(1, n) .map(m -> rangeClosed(1, m).reduce(1, (a,...
152Superpermutation minimisation
9java
wkvej
double kelvinToCelsius(double k){ return k - 273.15; } double kelvinToFahrenheit(double k){ return k * 1.8 - 459.67; } double kelvinToRankine(double k){ return k * 1.8; } void convertKelvin(double kelvin) { printf(, kelvin); printf(, kelvinToCelsius(kelvin)); printf(, kelvinToFahrenheit(kelvin...
157Temperature conversion
5c
ydb6f
local days = { 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', } local gifts = { "A partridge in a pear tree", "Two turtle doves", "Three french hens", "Four calling birds", "Five golden rings", "Six geese a-laying", ...
139The Twelve Days of Christmas
1lua
gl54j
import java.math.BigInteger; public class SuperDNumbers { public static void main(String[] args) { for ( int i = 2 ; i <= 9 ; i++ ) { superD(i, 10); } } private static final void superD(int d, int max) { long start = System.currentTimeMillis(); String test = ""...
153Super-d numbers
9java
k46hm
package main import ( "github.com/fogleman/gg" "math" ) func superEllipse(dc *gg.Context, n float64, a int) { hw := float64(dc.Width() / 2) hh := float64(dc.Height() / 2)
156Superellipse
0go
l3wcw
null
144Taxicab numbers
11kotlin
9tfmh
null
152Superpermutation minimisation
11kotlin
bgmkb
require 'prime' taus = Enumerator.new do |y| (1..).each do |n| num_divisors = n.prime_division.inject(1){|prod, n| prod *= n[1] + 1 } y << n if n % num_divisors == 0 end end p taus.take(100)
145Tau number
14ruby
ixeoh
use strict; use warnings; use feature 'say'; use ntheory 'divisors'; my @x; push @x, scalar divisors($_) for 1..100; say "Tau function - first 100:\n" . ((sprintf "@{['%4d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr);
147Tau function
2perl
593u2
import os os.system()
151Terminal control/Clear the screen
3python
prcbm
cat("\33[2J")
151Terminal control/Clear the screen
13r
ju678
package main import ( "bufio" "fmt" "log" "os" ) func main() { lines := make(chan string) count := make(chan int) go func() { c := 0 for l := range lines { fmt.Println(l) c++ } count <- c }() f, err := os.Open("input.txt") ...
149Synchronous concurrency
0go
pr2bg
bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { ...
158Summarize primes
5c
vyw2o
import java.math.BigInteger fun superD(d: Int, max: Int) { val start = System.currentTimeMillis() var test = "" for (i in 0 until d) { test += d } var n = 0 var i = 0 println("First $max super-$d numbers:") while (n < max) { i++ val value: Any = BigInteger.value...
153Super-d numbers
11kotlin
gld4d
import Reflex import Reflex.Dom import Data.Text (Text, pack, unpack) import Data.Map (Map, fromList, empty) import Text.Read (readMaybe) width = 600 height = 500 type Point = (Float,Float) type Segment = (Point,Point) data Ellipse = Ellipse {a :: Float, b :: Float, n :: Float} toFloat :: Text -> Maybe Float toFlo...
156Superellipse
8haskell
176ps
def sylvester(n) = (1..n).reduce(2){|a| a*a - a + 1 } (0..9).each {|n| puts } puts
155Sylvester's sequence
14ruby
ow48v
sums, taxis, limit = {}, {}, 1200 for i = 1, limit do for j = 1, i-1 do sum = i^3 + j^3 sums[sum] = sums[sum] or {} table.insert(sums[sum], i.."^3 + "..j.."^3") end end for k,v in pairs(sums) do if #v > 1 then table.insert(taxis, { sum=k, num=#v, terms=table.concat(v," = ") }) end end table.sort(taxis...
144Taxicab numbers
1lua
czt92
null
145Tau number
15rust
nqwi4
import Foundation
145Tau number
17swift
owa8k
import fileinput import sys nodata = 0; nodata_max=-1; nodata_maxline=[]; tot_file = 0 num_file = 0 infiles = sys.argv[1:] for line in fileinput.input(): tot_line=0; num_line=0; field = line.split() date = field[0] data =...
136Text processing/1
3python
c329q
import Control.Concurrent import Control.Concurrent.MVar main = do lineVar <- newEmptyMVar countVar <- newEmptyMVar let takeLine = takeMVar lineVar putLine = putMVar lineVar . Just putEOF = putMVar lineVar Nothing takeCount = takeMVar countVar putCou...
149Synchronous concurrency
8haskell
f0ad1
package main import "fmt" type point struct { x, y float32 } var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}} var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}} func main() { var cp1, cp2, s, e ...
154Sutherland-Hodgman polygon clipping
0go
7vfr2
const char *A[] = { , , , , }; const char *B[] = { , , , , }; void uniq(const char *x[], int len) { int i, j; for (i = 0; i < len; i++) for (j = i + 1; j < len; j++) if (x[j] && x[i] && !strcmp(x[i], x[j])) x[j] = 0; } int in_set(const char *const x[], int len, const char *match) { int i; for (i = 0; i ...
159Symmetric difference
5c
umwv4
for d = 2, 5 do local n, found = 0, {} local dds = string.rep(d, d) while #found < 10 do local dnd = string.format("%15.f", d * n ^ d) if string.find(dnd, dds) then found[#found+1] = n end n = n + 1 end print("super-" .. d .. ": " .. table.concat(found,", ")) end
153Super-d numbers
1lua
r2fga
import java.awt.*; import java.awt.geom.Path2D; import static java.lang.Math.pow; import java.util.Hashtable; import javax.swing.*; import javax.swing.event.*; public class SuperEllipse extends JPanel implements ChangeListener { private double exp = 2.5; public SuperEllipse() { setPreferredSize(new Di...
156Superellipse
9java
7vnrj
import BigNumber func sylvester(n: Int) -> BInt { var a = BInt(2) for _ in 0..<n { a = a * a - a + 1 } return a } var sum = BDouble(0) for n in 0..<10 { let syl = sylvester(n: n) sum += BDouble(1) / BDouble(syl) print(syl) } print("Sum of the reciprocals of first ten in sequence: \(sum)")
155Sylvester's sequence
17swift
8e50v
use ntheory qw/forperm/; for my $len (1..8) { my($pre, $post, $t) = ("",""); forperm { $t = join "",@_; $post .= $t unless index($post ,$t) >= 0; $pre = $t . $pre unless index($pre, $t) >= 0; } $len; printf "%2d:%8d%8d\n", $len, length($pre), length($post); }
152Superpermutation minimisation
2perl
6ne36
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n ...
147Tau function
3python
4c65k
package Trit; use Exporter 'import'; our @EXPORT_OK = qw(TRUE FALSE MAYBE is_true is_false is_maybe); our %EXPORT_TAGS = ( all => \@EXPORT_OK, const => [qw(TRUE FALSE MAYBE)], bool => [qw(is_true is_false is_maybe)], ); use List::Util qw(min max); use overload '=' => sub { $_[0]->clone() }, '<=>'=> sub { $_[0...
138Ternary logic
2perl
d0dnw
dfr <- read.delim("readings.txt") flags <- as.matrix(dfr[,seq(3,49,2)])>0 vals <- as.matrix(dfr[,seq(2,49,2)]) daily.means <- rowSums(ifelse(flags, vals, 0))/rowSums(flags) times <- strptime(dfr[1,1], "%Y-%m-%d", tz="GMT") + 3600*seq(1,24*nrow(dfr),1) hours.between.good.measurements <- diff(times[t(flags)])/3600
136Text processing/1
13r
6dm3e
import java.io.BufferedReader; import java.io.FileReader; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; class SynchronousConcurrency { public static void main(String[] args) ...
149Synchronous concurrency
9java
0ajse
module SuthHodgClip (clipTo) where import Data.List type Pt a = (a, a) type Ln a = (Pt a, Pt a) type Poly a = [Pt a] polyFrom ps = last ps: ps linesFrom pps@(_:ps) = zip pps ps (.|) :: (Num a, Ord a) => Pt a -> Ln a -> Bool (x,y) .| ((px,py),(qx,qy)) = (qx-px)*(y-py) >= (qy-py)*(x-px) (><) :: Fractional ...
154Sutherland-Hodgman polygon clipping
8haskell
8e40z
package main import ( "fmt" "io" "os" "strings" "time" ) func addNote(fn string, note string) error { f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return err } _, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n")
150Take notes on the command line
0go
xb4wf
var n = 2.5, a = 200, b = 200, ctx; function point( x, y ) { ctx.fillRect( x, y, 1, 1); } function start() { var can = document.createElement('canvas'); can.width = can.height = 600; ctx = can.getContext( "2d" ); ctx.rect( 0, 0, can.width, can.height ); ctx.fillStyle = "#000000"; ctx.fill(); ...
156Superellipse
10javascript
pr3b7
(defn to-celsius [k] (- k 273.15)) (defn to-fahrenheit [k] (- (* k 1.8) 459.67)) (defn to-rankine [k] (* k 1.8)) (defn temperature-conversion [k] (if (number? k) (format "Celsius:%.2f Fahrenheit:%.2f Rankine:%.2f" (to-celsius k) (to-fahrenheit k) (to-rankine k)) (format "Error: Non-numeric ...
157Temperature conversion
6clojure
26wl1
lengths(sapply(1:100, function(n) c(Filter(function(x) n %% x == 0, seq_len(n %/% 2)), n)))
147Tau function
13r
26flg
system 'clear'
151Terminal control/Clear the screen
14ruby
aj21s
print!("\x1B[2J");
151Terminal control/Clear the screen
15rust
ehvaj
object Cls extends App {print("\033[2J")}
151Terminal control/Clear the screen
16scala
qp4xw
import java.util.concurrent.SynchronousQueue import kotlin.concurrent.thread import java.io.File const val EOT = "\u0004"
149Synchronous concurrency
11kotlin
eh5a4
typedef struct rec_t rec_t; struct rec_t { int depth; rec_t * p[10]; }; rec_t root = {0, {0}}; rec_t *tail = 0, *head = 0; inline rec_t *new_rec() { if (head == tail) { head = calloc(sizeof(rec_t), POOL_SIZE); tail = head + POOL_SIZE; } return head++; } rec_t *find_rec(char *s) { int i; rec_t *r = &...
160Summarize and say sequence
5c
glq45
use strict; use warnings; use bigint; use feature 'say'; sub super { my $d = shift; my $run = $d x $d; my @super; my $i = 0; my $n = 0; while ( $i < 10 ) { if (index($n ** $d * $d, $run) > -1) { push @super, $n; ++$i; } ++$n; } @super; } ...
153Super-d numbers
2perl
nqjiw
def notes = new File('./notes.txt') if (args) { notes << "${new Date().format('YYYY-MM-dd HH:mm:ss')}\t${args.join(' ')}\n" } else { println notes.text }
150Take notes on the command line
7groovy
prlbo
import System.Environment (getArgs) import System.Time (getClockTime) main :: IO () main = do args <- getArgs if null args then catch (readFile "notes.txt" >>= putStr) (\_ -> return ()) else do ct <- getClockTime appendFile "notes.txt" $ show ct ++ "\n\t" ++ unwords args ++ "\...
150Take notes on the command line
8haskell
ydq66
null
156Superellipse
11kotlin
umsvc
from __future__ import print_function, division from itertools import permutations from math import factorial import string import datetime import gc MAXN = 7 def s_perm0(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in permutations(allchars)] sp, tofind = allperms[0], se...
152Superpermutation minimisation
3python
ydw6q
<?php if (! define('triFalse',0)) trigger_error('Unknown error defining!', E_USER_ERROR); if (! define('triMaybe',1)) trigger_error('Unknown error defining!', E_USER_ERROR); if (! define('triTrue', 2)) trigger_error('Unknown error defining!', E_USER_ERROR); $triNotarray = array(triFalse=>triTrue, triMaybe=>triMay...
138Ternary logic
12php
j5j7z
function ReadFile() local fp = io.open( "input.txt" ) assert( fp ~= nil ) for line in fp:lines() do coroutine.yield( line ) end fp:close() end co = coroutine.create( ReadFile ) while true do local status, val = coroutine.resume( co ) if coroutine.status( co ) == "dead" then break end ...
149Synchronous concurrency
1lua
wk4ea
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum, n, c := 0, 0, 0 fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:") fmt.Println(" n cumulative sum") for _, p := range primes { n++ sum += p if rcu.IsPri...
158Summarize primes
0go
s1cqa
import Data.List (scanl) import Data.Numbers.Primes (isPrime, primes) indexedPrimeSums :: [(Integer, Integer, Integer)] indexedPrimeSums = filter (\(_, _, n) -> isPrime n) $ scanl (\(i, _, m) p -> (succ i, p, p + m)) (0, 0, 0) primes main :: IO () main = mapM_ print $ takeWhile (\(_, ...
158Summarize primes
8haskell
9tpmo
import java.awt.*; import java.awt.geom.Line2D; import java.util.*; import java.util.List; import javax.swing.*; public class SutherlandHodgman extends JFrame { SutherlandHodgmanPanel panel; public static void main(String[] args) { JFrame f = new SutherlandHodgman(); f.setDefaultCloseOperatio...
154Sutherland-Hodgman polygon clipping
9java
ehca5
(use '[clojure.set]) (defn symmetric-difference [s1 s2] (union (difference s1 s2) (difference s2 s1))) (symmetric-difference #{:john:bob:mary:serena} #{:jim:mary:john:bob})
159Symmetric difference
6clojure
7v8r0
from itertools import islice, count def superd(d): if d != int(d) or not 2 <= d <= 9: raise ValueError() tofind = str(d) * d for n in count(2): if tofind in str(d * n ** d): yield n if __name__ == '__main__': for d in range(2, 9): print(f, ', '.join(str(n) for n in ...
153Super-d numbers
3python
dshn1
library(Rmpfr) options(scipen = 999) find_super_d_number <- function(d, N = 10){ super_number <- c(NA) n = 0 n_found = 0 while(length(super_number) < N){ n = n + 1 test = d * mpfr(n, precBits = 200) ** d test_formatted = .mpfr2str(test)$str iterable = strsplit(test_formatted, "")[[...
153Super-d numbers
13r
8eg0x
my($beg, $end) = (@ARGV==0) ? (1,25) : (@ARGV==1) ? (1,shift) : (shift,shift); my $lim = 1e14; my @basis = map { $_*$_*$_ } (1 .. int($lim ** (1.0/3.0) + 1)); my $paira = 2; my ($segsize, $low, $high, $i) = (500_000_000, 0, 0, 0); while ($i < $end) { $low = $high+1; die "lim too low" if $low > $lim; $high ...
144Taxicab numbers
2perl
wkhe6
require 'prime' def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp + 1} (1..100).map{|n| tau(n).to_s.rjust(3) }.each_slice(20){|ar| puts ar.join}
147Tau function
14ruby
r2mgs
null
147Tau function
15rust
7v9rc
(defmacro reduce-with "simplifies form of reduce calls" [bindings & body] (assert (and (vector? bindings) (= 4 (count bindings)))) (let [[acc init, item sequence] bindings] `(reduce (fn [~acc ~item] ~@body) ~init ~sequence))) (defn digits "maps e.g. 2345 => [2 3 4 5]" [n] (->> n str seq (map #(- (int %...
160Summarize and say sequence
6clojure
k4ihs
<html> <head> <script> function clip (subjectPolygon, clipPolygon) { var cp1, cp2, s, e; var inside = function (p) { return (cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0]); }; var intersection = function () { var...
154Sutherland-Hodgman polygon clipping
10javascript
0a5sz
(2..8).each do |d| rep = d.to_s * d print puts (2..).lazy.select{|n| (d * n**d).to_s.include?(rep) }.first(10).join() end
153Super-d numbers
14ruby
t8bf2
import java.io.*; import java.nio.channels.*; import java.util.Date; public class TakeNotes { public static void main(String[] args) throws IOException { if (args.length > 0) { PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true)); ps.println(new Date()); ...
150Take notes on the command line
9java
dspn9
local abs,cos,floor,pi,pow,sin = math.abs,math.cos,math.floor,math.pi,math.pow,math.sin local bitmap = { init = function(self, w, h, value) self.w, self.h, self.pixels = w, h, {} for y=1,h do self.pixels[y]={} end self:clear(value) end, clear = function(self, value) for y=1,self.h do for x=1...
156Superellipse
1lua
590u6
import Foundation
147Tau function
17swift
gly49
filename = total = { => 0, => 0, => 0.0 } invalid_count = 0 max_invalid_count = 0 invalid_run_end = File.new(filename).each do |line| num_readings = 0 num_good_readings = 0 sum_readings = 0.0 fields = line.split fields[1..-1].each_slice(2) do |reading, flag| num_readings += 1 if Integer(flag) >...
136Text processing/1
14ruby
2yulw
use v5.10; my @days = qw{ first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth }; chomp ( my @gifts = grep { /\S/ } <DATA> ); while ( my $day = shift @days ) { say "On the $day day of Christmas,\nMy true love gave to me:"; say for map { $day eq 'first' ? s/And a/A/r : $_ } @gift...
139The Twelve Days of Christmas
2perl
ix8o3
use strict; use warnings; use ntheory <nth_prime is_prime>; my($n, $s, $limit, @sums) = (0, 0, 1000); do { push @sums, sprintf '%3d%8d', $n, $s if is_prime($s += nth_prime ++$n) } until $n >= $limit; print "Of the first $limit primes: @{[scalar @sums]} cumulative prime sums:\n", join "\n", @sums;
158Summarize primes
2perl
gl04e
null
154Sutherland-Hodgman polygon clipping
11kotlin
k43h3
null
153Super-d numbers
15rust
zopto
import BigInt import Foundation let rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"] for d in 2...9 { print("First 10 super-\(d) numbers:") var count = 0 var n = BigInt(3) var k = BigInt(0) while true { k = n.power(d) k *= BigInt(d) if let _ = String(k).range(...
153Super-d numbers
17swift
f0kdk
var notes = 'NOTES.TXT'; var args = WScript.Arguments; var fso = new ActiveXObject("Scripting.FileSystemObject"); var ForReading = 1, ForWriting = 2, ForAppending = 8; if (args.length == 0) { if (fso.FileExists(notes)) { var f = fso.OpenTextFile(notes, ForReading); WScript.Echo(f.ReadAll()); ...
150Take notes on the command line
10javascript
6nx38