code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
int main(){
int sum = 0, i, j;
int try_max = 0;
int count_list[3] = {1,0,0};
for(i=2; i <= 20000; i++){
try_max = i/2;
sum = 1;
for(j=2; j<try_max; j++){
if (i % j)
continue;
try_max = i/j;
sum += j;
if (j != try_max)
sum += try_max;
}
if (sum < i){
count_l... | 1,161Abundant, deficient and perfect number classifications | 5c | 08bst |
(ns rosettacode.align-columns
(:require [clojure.contrib.string:as str]))
(def data "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space... | 1,160Align columns | 6clojure | ymi6b |
use strict;
use 5.10.0;
package Integrator;
use threads;
use threads::shared;
sub new {
my $cls = shift;
my $obj = bless { t => 0,
sum => 0,
ref $cls ? %$cls : (),
stop => 0,
tid => 0,
func => shift,
}, ref $cls || $cls;
share($obj->{sum});
share($obj->{stop});
$obj->{tid} = async {
my... | 1,157Active object | 2perl | cl39a |
from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new = pdsum(s... | 1,151Aliquot sequence classifications | 3python | g774h |
null | 1,153AKS test for primes | 11kotlin | v5v21 |
from proper_divisors import proper_divs
def amicable(rangemax=20000):
n2divsum = {n: sum(proper_divs(n)) for n in range(1, rangemax + 1)}
for num, divsum in n2divsum.items():
if num < divsum and divsum <= rangemax and n2divsum[divsum] == num:
yield num, divsum
if __name__ == '__main__':
... | 1,144Amicable pairs | 3python | c279q |
def accumulator = { Number n ->
def value = n;
{ it = 0 -> value += it}
} | 1,159Accumulator factory | 7groovy | 081sh |
null | 1,153AKS test for primes | 1lua | u4uvl |
require
additive_primes = Prime.lazy.select{|prime| prime.digits.sum.prime? }
N = 500
res = additive_primes.take_while{|n| n < N}.to_a
puts res.join()
puts | 1,154Additive primes | 14ruby | gr54q |
import Control.Monad.ST
import Data.STRef
accumulator :: (Num a) => a -> ST s (a -> ST s a)
accumulator sum0 = do
sum <- newSTRef sum0
return $ \n -> do
modifySTRef sum (+ n)
readSTRef sum
main :: IO ()
main = print foo
where foo = runST $ do
x <- accumulator 1
x 5
... | 1,159Accumulator factory | 8haskell | 54mug |
fn main() {
let limit = 500;
let column_w = limit.to_string().len() + 1;
let mut pms = Vec::with_capacity(limit / 2 - limit / 3 / 2 - limit / 5 / 3 / 2 + 1);
let mut count = 0;
for u in (2..3).chain((3..limit).step_by(2)) {
if pms.iter().take_while(|&&p| p * p <= u).all(|&p| u % p != 0) {
... | 1,154Additive primes | 15rust | r74g5 |
divisors <- function (n) {
Filter( function (m) 0 == n%% m, 1:(n/2) )
}
table = sapply(1:19999, function (n) sum(divisors(n)) )
for (n in 1:19999) {
m = table[n]
if ((m > n) && (m < 20000) && (n == table[m]))
cat(n, " ", m, "\n")
} | 1,144Amicable pairs | 13r | 6m53e |
use strict;
use warnings;
use constant EXIT_FAILURE => 1;
use constant EXIT_SUCCESS => 0;
sub amb {
exit(EXIT_FAILURE) if !@_;
for my $word (@_) {
my $pid = fork;
die $! unless defined $pid;
return $word if !$pid;
my $wpid = waitpid $pid, 0;
die $! unless $wpid == $pid;
exit(... | 1,148Amb | 2perl | fzyd7 |
from time import time, sleep
from threading import Thread
class Integrator(Thread):
'continuously integrate a function `K`, at each `interval` seconds'
def __init__(self, K=lambda t:0, interval=1e-4):
Thread.__init__(self)
self.interval = interval
self.K = K
self.S = 0.0
... | 1,157Active object | 3python | l26cv |
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"sort"
)
func main() {
r, err := http.Get("http: | 1,152Anagrams | 0go | 6my3p |
def fib(n)
raise RangeError, if n < 0
(fib2 = proc { |m| m < 2? m: fib2[m - 1] + fib2[m - 2] })[n]
end | 1,138Anonymous recursion | 14ruby | jki7x |
public class Accumulator | 1,159Accumulator factory | 9java | 9cfmu |
(defn pad-class
[n]
(let [divs (filter #(zero? (mod n %)) (range 1 n))
divs-sum (reduce + divs)]
(cond
(< divs-sum n):deficient
(= divs-sum n):perfect
(> divs-sum n):abundant)))
(def pad-classes (map pad-class (map inc (range))))
(defn count-classes
[n]
(let [classes (take n pad-... | 1,161Abundant, deficient and perfect number classifications | 6clojure | dfwnb |
import Foundation
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
if n% 2 == 0 {
return n == 2
}
if n% 3 == 0 {
return n == 3
}
var p = 5
while p * p <= n {
if n% p == 0 {
return false
}
p += 2
if n% p == 0 {... | 1,154Additive primes | 17swift | 4gu5g |
from prime_decomposition import decompose
from itertools import islice, count
try:
from functools import reduce
except:
pass
def almostprime(n, k=2):
d = decompose(n)
try:
terms = [next(d) for i in range(k)]
return reduce(int.__mul__, terms, 1) == n
except:
return False
... | 1,147Almost prime | 3python | nf6iz |
def words = new URL('http: | 1,152Anagrams | 7groovy | dtfn3 |
fn fib(n: i64) -> Option<i64> { | 1,138Anonymous recursion | 15rust | hbnj2 |
function accumulator(sum) {
return function(n) {
return sum += n;
}
}
var x = accumulator(1);
x(5);
console.log(accumulator(3).toString() + '<br>');
console.log(x(2.3)); | 1,159Accumulator factory | 10javascript | u5yvb |
#![feature(mpsc_select)]
extern crate num;
extern crate schedule_recv;
use num::traits::Zero;
use num::Float;
use schedule_recv::periodic_ms;
use std::f64::consts::PI;
use std::ops::Mul;
use std::sync::mpsc::{self, SendError, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
pub type Ac... | 1,157Active object | 15rust | u59vj |
object ActiveObject {
class Integrator {
import java.util._
import scala.actors.Actor._
case class Pulse(t: Double)
case class Input(k: Double => Double)
case object Output
case object Bye
val timer = new Timer(true)
var k: Double => Double = (_ => 0.0)
var s: Double = 0.0
... | 1,157Active object | 16scala | gr24i |
findfactors <- function(n) {
d <- c()
div <- 2; nxt <- 3; rest <- n
while( rest != 1 ) {
while( rest%%div == 0 ) {
d <- c(d, div)
rest <- floor(rest / div)
}
div <- nxt
nxt <- nxt + 2
}
d
}
almost_primes <- function(n = 10, k = 5) {
res <- matrix(NA, nrow = k, ncol = n)... | 1,147Almost prime | 13r | 0ofsg |
import Data.List
groupon f x y = f x == f y
main = do
f <- readFile "./../Puzzels/Rosetta/unixdict.txt"
let words = lines f
wix = groupBy (groupon fst) . sort $ zip (map sort words) words
mxl = maximum $ map length wix
mapM_ (print . map snd) . filter ((==mxl).length) $ wix | 1,152Anagrams | 8haskell | jkh7g |
def Y[A, B](f: (A B) (A B)): A B = f(Y(f))(_)
def fib(n: Int): Option[Int] =
if (n < 0) None
else Some(Y[Int, Int](f i
if (i < 2) 1
else f(i - 1) + f(i - 2))(n))
-2 to 5 map (n (n, fib(n))) foreach println | 1,138Anonymous recursion | 16scala | patbj |
null | 1,159Accumulator factory | 11kotlin | z38ts |
def aliquot(n, maxlen=16, maxterm=2**47)
return , [0] if n == 0
s = []
while (s << n).size <= maxlen and n < maxterm
n = n.proper_divisors.inject(0,:+)
if s.include?(n)
case n
when s[0]
case s.size
when 1 then return , s
when 2 then return , s
else ... | 1,151Aliquot sequence classifications | 14ruby | 7hhri |
null | 1,157Active object | 17swift | 2vylj |
#[derive(Debug)]
enum AliquotType { Terminating, Perfect, Amicable, Sociable, Aspiring, Cyclic, NonTerminating }
fn classify_aliquot(num: i64) -> (AliquotType, Vec<i64>) {
let limit = 1i64 << 47; | 1,151Aliquot sequence classifications | 15rust | jkk72 |
function acc(init)
init = init or 0
return function(delta)
init = init + (delta or 0)
return init
end
end | 1,159Accumulator factory | 1lua | 36ozo |
def createAliquotSeq(n: Long, step: Int, list: List[Long]): (String, List[Long]) = {
val sum = properDivisors(n).sum
if (sum == 0) ("terminate", list ::: List(sum))
else if (step >= 16 || sum > 140737488355328L) ("non-term", list)
else {
list.indexOf(sum) match {
case -1 => createAli... | 1,151Aliquot sequence classifications | 16scala | b11k6 |
require 'prime'
def almost_primes(k=2)
return to_enum(:almost_primes, k) unless block_given?
1.step {|n| yield n if n.prime_division.sum( &:last ) == k }
end
(1..5).each{|k| puts almost_primes(k).take(10).join()} | 1,147Almost prime | 14ruby | fzmdr |
import java.net.*;
import java.io.*;
import java.util.*;
public class WordsOfEqChars {
public static void main(String[] args) throws IOException {
URL url = new URL("http: | 1,152Anagrams | 9java | u45vv |
import itertools as _itertools
class Amb(object):
def __init__(self):
self._names2values = {}
self._func = None
self._valueiterator = None
self._funcargnames = None
def __call__(self, arg=None):
if hasattr(arg, '__code__'): ... | 1,148Amb | 3python | t3mfw |
extension BinaryInteger {
@inlinable
public func factors(sorted: Bool = true) -> [Self] {
let maxN = Self(Double(self).squareRoot())
var res = Set<Self>()
for factor in stride(from: 1, through: maxN, by: 1) where self% factor == 0 {
res.insert(factor)
res.insert(self / factor)
}
re... | 1,151Aliquot sequence classifications | 17swift | rjjgg |
fn is_kprime(n: u32, k: u32) -> bool {
let mut primes = 0;
let mut f = 2;
let mut rem = n;
while primes < k && rem > 1{
while (rem% f) == 0 && rem > 1{
rem /= f;
primes += 1;
}
f += 1;
}
rem == 1 && primes == k
}
struct KPrimeGen {
k: u32,
... | 1,147Almost prime | 15rust | t39fd |
def isKPrime(n: Int, k: Int, d: Int = 2): Boolean = (n, k, d) match {
case (n, k, _) if n == 1 => k == 0
case (n, _, d) if n % d == 0 => isKPrime(n / d, k - 1, d)
case (_, _, _) => isKPrime(n, k, d + 1)
}
def kPrimeStream(k: Int): Stream[Int] = {
def loop(n: Int): Stream[Int] =
if (isKPrime(n, ... | 1,147Almost prime | 16scala | 6m231 |
var fs = require('fs');
var words = fs.readFileSync('unixdict.txt', 'UTF-8').split('\n');
var i, item, max = 0,
anagrams = {};
for (i = 0; i < words.length; i += 1) {
var key = words[i].split('').sort().join('');
if (!anagrams.hasOwnProperty(key)) { | 1,152Anagrams | 10javascript | 7hjrd |
h = {}
(1..20_000).each{|n| h[n] = n.proper_divisors.sum }
h.select{|k,v| h[v] == k && k < v}.each do |key,val|
puts
end | 1,144Amicable pairs | 14ruby | 2uhlw |
checkSentence <- function(sentence){
for (index in 1:(length(sentence)-1)){
first.word <- sentence[index]
second.word <- sentence[index+1]
last.letter <- substr(first.word, nchar(first.word), nchar(first.word))
first.letter <- substr(second.word, 1, 1)
if (last.letter!= first.letter){ return... | 1,148Amb | 13r | idzo5 |
fn sum_of_divisors(val: u32) -> u32 {
(1..val/2+1).filter(|n| val% n == 0)
.fold(0, |sum, n| sum + n)
}
fn main() {
let iter = (1..20_000).map(|i| (i, sum_of_divisors(i)))
.filter(|&(i, div_sum)| i > div_sum);
for (i, sum1) in iter {
if sum_of_divisors(sum... | 1,144Amicable pairs | 15rust | v5k2t |
use strict;
use warnings;
use Math::BigInt; sub binomial { Math::BigInt->new(shift)->bnok(shift) }
sub binprime {
my $p = shift;
return 0 unless $p >= 2;
for (1 .. ($p>>1)) { return 0 if binomial($p,$_) % $p }
1;
}
sub coef {
my($n,$e) = @_;
return $n unless $e;
$n = "" if $n==1... | 1,153AKS test for primes | 2perl | 0o0s4 |
struct KPrimeGen: Sequence, IteratorProtocol {
let k: Int
private(set) var n: Int
private func isKPrime() -> Bool {
var primes = 0
var f = 2
var rem = n
while primes < k && rem > 1 {
while rem% f == 0 && rem > 1 {
rem /= f
primes += 1
}
f += 1
}
return... | 1,147Almost prime | 17swift | dtynh |
def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0)
val divisorsSum = (1 to 20000).map(i => i -> properDivisors(i).sum).toMap
val result = divisorsSum.filter(v => v._1 < v._2 && divisorsSum.get(v._2) == Some(v._1))
println( result mkString ", " ) | 1,144Amicable pairs | 16scala | 4r150 |
null | 1,147Almost prime | 20typescript | 5ghu4 |
let fib: Int -> Int = {
func f(n: Int) -> Int {
assert(n >= 0, "fib: no negative numbers")
return n < 2? 1: f(n-1) + f(n-2)
}
return f
}()
print(fib(8)) | 1,138Anonymous recursion | 17swift | 7horq |
require
class Amb
class ExhaustedError < RuntimeError; end
def initialize
@fail = proc { fail ExhaustedError, }
end
def choose(*choices)
prev_fail = @fail
callcc { |sk|
choices.each { |choice|
callcc { |fk|
@fail = proc {
@fail = prev_fail
fk.call(:fail)
}
if choice.re... | 1,148Amb | 14ruby | 3ycz7 |
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.URL
import kotlin.math.max
fun main() {
val url = URL("http: | 1,152Anagrams | 11kotlin | 9lcmh |
use std::ops::Add;
struct Amb<'a> {
list: Vec<Vec<&'a str>>,
}
fn main() {
let amb = Amb {
list: vec![
vec!["the", "that", "a"],
vec!["frog", "elephant", "thing"],
vec!["walked", "treaded", "grows"],
vec!["slowly", "quickly"],
],
};
match a... | 1,148Amb | 15rust | 6ml3l |
import func Darwin.sqrt
func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) }
func properDivs(n: Int) -> [Int] {
if n == 1 { return [] }
var result = [Int]()
for div in filter (1...sqrt(n), { n% $0 == 0 }) {
result.append(div)
if n/div!= div && n/div!= n { result.append(n/div) }
... | 1,144Amicable pairs | 17swift | lvjc2 |
object Amb {
def amb(wss: List[List[String]]): Option[String] = {
def _amb(ws: List[String], wss: List[List[String]]): Option[String] = wss match {
case Nil => ((Some(ws.head): Option[String]) /: ws.tail)((a, w) => a match {
case Some(x) => if (x.last == w.head) Some(x + " " + w) else None
... | 1,148Amb | 16scala | 9lum5 |
sub accumulator {
my $sum = shift;
sub { $sum += shift }
}
my $x = accumulator(1);
$x->(5);
accumulator(3);
print $x->(2.3), "\n"; | 1,159Accumulator factory | 2perl | bp4k4 |
package main
import (
"fmt"
"strings"
)
const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$eac... | 1,160Align columns | 0go | jh27d |
def expand_x_1(n):
c =1
for i in range(n
c = c*(n-i)
yield c
def aks(p):
if p==2:
return True
for i in expand_x_1(p):
if i% p:
return False
return True | 1,153AKS test for primes | 3python | 8i80o |
function sort(word)
local bytes = {word:byte(1, -1)}
table.sort(bytes)
return string.char(table.unpack(bytes))
end | 1,152Anagrams | 1lua | c2l92 |
<?php
function accumulator($start){
return create_function('$x','static $v='.$start.';return $v+=$x;');
}
$acc = accumulator(5);
echo $acc(5), ;
echo $acc(10), ;
?> | 1,159Accumulator factory | 12php | 6yi3g |
int ackermann(int m, int n)
{
if (!m) return n + 1;
if (!n) return ackermann(m - 1, 1);
return ackermann(m - 1, ackermann(m, n - 1));
}
int main()
{
int m, n;
for (m = 0; m <= 4; m++)
for (n = 0; n < 6 - m; n++)
printf(, m, n, ackermann(m,... | 1,162Ackermann function | 5c | dfenv |
def alignColumns = { align, rawText ->
def lines = rawText.tokenize('\n')
def words = lines.collect { it.tokenize(/\$/) }
def maxLineWords = words.collect {it.size()}.max()
words = words.collect { line -> line + [''] * (maxLineWords - line.size()) }
def columnWidths = words.transpose().collect{ colu... | 1,160Align columns | 7groovy | 54yuv |
AKS<-function(p){
i<-2:p-1
l<-unique(factorial(p) / (factorial(p-i) * factorial(i)))
if(all(l%%p==0)){
print(noquote("It is prime."))
}else{
print(noquote("It isn't prime."))
}
} | 1,153AKS test for primes | 13r | xsxw2 |
import Data.List (unfoldr, transpose)
import Control.Arrow (second)
dat =
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" ++
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n" ++
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" ++
"column$are$separated$by$a... | 1,160Align columns | 8haskell | oia8p |
>>> def accumulator(sum):
def f(n):
f.sum += n
return f.sum
f.sum = sum
return f
>>> x = accumulator(1)
>>> x(5)
6
>>> x(2.3)
8.3000000000000007
>>> x = accumulator(1)
>>> x(5)
6
>>> x(2.3)
8.3000000000000007
>>> x2 = accumulator(3)
>>> x2(5)
8
>>> x2(3.3)
11.300000000000001
>>> x(0)
8.3000000000000007
>... | 1,159Accumulator factory | 3python | p1gbm |
require 'polynomial'
def x_minus_1_to_the(p)
return Polynomial.new(-1,1)**p
end
def prime?(p)
return false if p < 2
(x_minus_1_to_the(p) - Polynomial.from_string()).coefs.all?{|n| n%p==0}
end
8.times do |n|
puts
end
puts , 50.times.select {|n| prime? n}.join(',') | 1,153AKS test for primes | 14ruby | idioh |
accumulatorFactory <- function(init) {
currentSum <- init
function(add) {
currentSum <<- currentSum + add
currentSum
}
} | 1,159Accumulator factory | 13r | jhv78 |
fn aks_coefficients(k: usize) -> Vec<i64> {
let mut coefficients = vec![0i64; k + 1];
coefficients[0] = 1;
for i in 1..(k + 1) {
coefficients[i] = -(1..i).fold(coefficients[0], |prev, j|{
let old = coefficients[j];
coefficients[j] = old - prev;
old
});
... | 1,153AKS test for primes | 15rust | nfni4 |
package main
import "fmt"
func pfacSum(i int) int {
sum := 0
for p := 1; p <= i/2; p++ {
if i%p == 0 {
sum += p
}
}
return sum
}
func main() {
var d, a, p = 0, 0, 0
for i := 1; i <= 20000; i++ {
j := pfacSum(i)
if j < i {
d++
} e... | 1,161Abundant, deficient and perfect number classifications | 0go | u53vt |
def powerMin1(n: BigInt) = if (n % 2 == 0) BigInt(1) else BigInt(-1)
val pascal = (( Vector(Vector(BigInt(1))) /: (1 to 50)) { (rows, i) =>
val v = rows.head
val newVector = ((1 until v.length) map (j =>
powerMin1(j+i) * (v(j-1).abs + v(j).abs))
).toVector
(powerMin1(i) +: newVector :+ powerMin... | 1,153AKS test for primes | 16scala | t3tfb |
(defn ackermann [m n]
(cond (zero? m) (inc n)
(zero? n) (ackermann (dec m) 1)
:else (ackermann (dec m) (ackermann m (dec n))))) | 1,162Ackermann function | 6clojure | 6y03q |
def dpaCalc = { factors ->
def n = factors.pop()
def fSum = factors.sum()
fSum < n
? 'deficient'
: fSum > n
? 'abundant'
: 'perfect'
}
(1..20000).inject([deficient:0, perfect:0, abundant:0]) { map, n ->
map[dpaCalc(factorize(n))]++
map
}
.each { e -> println e ... | 1,161Abundant, deficient and perfect number classifications | 7groovy | 9cnm4 |
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
public class ColumnAligner {
private List<String[]> words = new ArrayList<>();
private ... | 1,160Align columns | 9java | wxjej |
def accumulator(sum)
lambda {|n| sum += n}
end
x = accumulator(1)
x.call(5)
accumulator(3)
puts x.call(2.3) | 1,159Accumulator factory | 14ruby | ae71s |
divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
classOf :: (Integral a) => a -> Ordering
classOf n = compare (sum $ divisors n) n
main :: IO ()
main = do
let classes = map classOf [1 .. 20000 :: Int]
printRes w c = putStrLn $ w ++ (show . length $ filter (== c)... | 1,161Abundant, deficient and perfect number classifications | 8haskell | wx7ed |
var justification="center",
input=["Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
"column$are$separated$by$at$least$one$space.",
"Further,$allow$for$each$word$in$a$colu... | 1,160Align columns | 10javascript | 8o10l |
null | 1,159Accumulator factory | 15rust | ewjaj |
def AccumulatorFactory[N](n: N)(implicit num: Numeric[N]) = {
import num._
var acc = n
(inc: N) => {
acc = acc + inc
acc
}
} | 1,159Accumulator factory | 16scala | qsbxw |
import java.util.stream.LongStream;
public class NumberClassifications {
public static void main(String[] args) {
int deficient = 0;
int perfect = 0;
int abundant = 0;
for (long i = 1; i <= 20_000; i++) {
long sum = properDivsSum(i);
if (sum < i)
... | 1,161Abundant, deficient and perfect number classifications | 9java | kbvhm |
func polynomialCoeffs(n: Int) -> [Int] {
var result = [Int](count: n+1, repeatedValue: 0)
result[0]=1
for i in 1 ..< n/2+1 { | 1,153AKS test for primes | 17swift | ono8k |
for (var dpa=[1,0,0], n=2; n<=20000; n+=1) {
for (var ds=0, d=1, e=n/2+1; d<e; d+=1) if (n%d==0) ds+=d
dpa[ds<n ? 0 : ds==n ? 1 : 2]+=1
}
document.write('Deficient:',dpa[0], ', Perfect:',dpa[1], ', Abundant:',dpa[2], '<br>' ) | 1,161Abundant, deficient and perfect number classifications | 10javascript | ewrao |
func makeAccumulator(var sum: Double) -> Double -> Double {
return {
sum += $0
return sum
}
}
let x = makeAccumulator(1)
x(5)
let _ = makeAccumulator(3)
println(x(2.3)) | 1,159Accumulator factory | 17swift | 1arpt |
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
enum class AlignFunction {
LEFT { override fun invoke(s: String, l: Int) = ("%-" + l + 's').format(("%" + s.length + 's').format(s)) },
RIGHT { override fun invoke(s: String, l: Int) = ("%-" + l + 's').format(("%" + ... | 1,160Align columns | 11kotlin | bp5kb |
null | 1,161Abundant, deficient and perfect number classifications | 11kotlin | grm4d |
local tWord = {} | 1,160Align columns | 1lua | p14bw |
use List::Util 'max';
my @words = split "\n", do { local( @ARGV, $/ ) = ( 'unixdict.txt' ); <> };
my %anagram;
for my $word (@words) {
push @{ $anagram{join '', sort split '', $word} }, $word;
}
my $count = max(map {scalar @$_} values %anagram);
for my $ana (values %anagram) {
print "@$ana\n" if @$ana == $cou... | 1,152Anagrams | 2perl | wqxe6 |
int A(int m, int n) => m==0? n+1: n==0? A(m-1,1): A(m-1,A(m,n-1));
main() {
print(A(0,0));
print(A(1,0));
print(A(0,1));
print(A(2,2));
print(A(2,3));
print(A(3,3));
print(A(3,4));
print(A(3,5));
print(A(4,0));
} | 1,162Ackermann function | 18dart | s0hq6 |
function sumDivs (n)
if n < 2 then return 0 end
local sum, sr = 1, math.sqrt(n)
for d = 2, sr do
if n % d == 0 then
sum = sum + d
if d ~= sr then sum = sum + n / d end
end
end
return sum
end
local a, d, p, Pn = 0, 0, 0
for n = 1, 20000 do
Pn = sumDivs(n)
... | 1,161Abundant, deficient and perfect number classifications | 1lua | r79ga |
<?php
$words = explode(, file_get_contents('http:
foreach ($words as $word) {
$chars = str_split($word);
sort($chars);
$anagram[implode($chars)][] = $word;
}
$best = max(array_map('count', $anagram));
foreach ($anagram as $ana)
if (count($ana) == $best)
print_r($ana);
?> | 1,152Anagrams | 12php | lv2cj |
use ntheory qw/divisor_sum/;
my @type = <Perfect Abundant Deficient>;
say join "\n", map { sprintf "%2d%s", $_, $type[divisor_sum($_)-$_ <=> $_] } 1..12;
my %h;
$h{divisor_sum($_)-$_ <=> $_}++ for 1..20000;
say "Perfect: $h{0} Deficient: $h{-1} Abundant: $h{1}"; | 1,161Abundant, deficient and perfect number classifications | 2perl | ndeiw |
>>> import urllib.request
>>> from collections import defaultdict
>>> words = urllib.request.urlopen('http:
>>> anagram = defaultdict(list)
>>> for word in words:
anagram[tuple(sorted(word))].append( word )
>>> count = max(len(ana) for ana in anagram.values())
>>> for ana in anagram.values():
if len(ana) >= count:... | 1,152Anagrams | 3python | xsqwr |
words <- readLines("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
word_group <- sapply(
strsplit(words, split=""),
function(x) paste(sort(x), collapse="")
)
counts <- tapply(words, word_group, length)
anagrams <- tapply(words, word_group, paste, collapse=", ")
table(counts)
counts
1 2 ... | 1,152Anagrams | 13r | 1eapn |
use strict ;
die "Call: perl columnaligner.pl <inputfile> <printorientation>!\n" unless
@ARGV == 2 ;
die "last argument must be one of center, left or right!\n" unless
$ARGV[ 1 ] =~ /center|left|right/ ;
sub printLines( $$$ ) ;
open INFILE , "<" , "$ARGV[ 0 ]" or die "Can't open $ARGV[ 0 ]!\n" ;
my @lines = <IN... | 1,160Align columns | 2perl | 6yo36 |
>>> from proper_divisors import proper_divs
>>> from collections import Counter
>>>
>>> rangemax = 20000
>>>
>>> def pdsum(n):
... return sum(proper_divs(n))
...
>>> def classify(n, p):
... return 'perfect' if n == p else 'abundant' if p > n else 'deficient'
...
>>> classes = Counter(classify(n, pdsum(n)) f... | 1,161Abundant, deficient and perfect number classifications | 3python | dfwn1 |
require(numbers);
propdivcls <- function(n) {
V <- sapply(1:n, Sigma, proper = TRUE);
c1 <- c2 <- c3 <- 0;
for(i in 1:n){
if(V[i]<i){c1 = c1 +1} else if(V[i]==i){c2 = c2 +1} else{c3 = c3 +1}
}
cat(" *** Between 1 and ", n, ":\n");
cat(" * ", c1, "deficient numbers\n");
cat(" * ", c2, "perfect num... | 1,161Abundant, deficient and perfect number classifications | 13r | 8op0x |
<?php
$j2justtype = array('L' => STR_PAD_RIGHT,
'R' => STR_PAD_LEFT,
'C' => STR_PAD_BOTH);
function aligner($str, $justification = 'L') {
global $j2justtype;
assert(array_key_exists($justification, $j2justtype));
$justtype = $j2justtype[$justification];
$fieldsbyrow = ... | 1,160Align columns | 12php | 1agpq |
require 'open-uri'
anagram = Hash.new {|hash, key| hash[key] = []}
URI.open('http:
words = f.read.split
for word in words
anagram[word.split('').sort] << word
end
end
count = anagram.values.map {|ana| ana.length}.max
anagram.each_value do |ana|
if ana.length >= count
p ana
end
end | 1,152Anagrams | 14ruby | s80qw |
res = (1 .. 20_000).map{|n| n.proper_divisors.sum <=> n }.tally
puts | 1,161Abundant, deficient and perfect number classifications | 14ruby | tzqf2 |
fn main() { | 1,161Abundant, deficient and perfect number classifications | 15rust | z3sto |
def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0)
def classifier(i: Int) = properDivisors(i).sum compare i
val groups = (1 to 20000).groupBy( classifier )
println("Deficient: " + groups(-1).length)
println("Abundant: " + groups(1).length)
println("Perfect: " + groups(0).length + " (" + groups(0).mkString(... | 1,161Abundant, deficient and perfect number classifications | 16scala | ymo63 |
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead,BufReader};
use std::borrow::ToOwned;
extern crate unicode_segmentation;
use unicode_segmentation::{UnicodeSegmentation};
fn main () {
let file = BufReader::new(File::open("unixdict.txt").unwrap());
let mut map = HashMap::new();
for l... | 1,152Anagrams | 15rust | 0o8sl |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.