code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
my ($board_size, @occupied, @past, @solutions); sub try_column { my ($depth, @diag) = shift; if ($depth == $board_size) { push @solutions, "@past\n"; return; } $ for (0 .. $ $diag[ $past[$_] + $depth - $...
543N-queens problem
2perl
5oqu2
null
540N'th
20typescript
meayd
local M = {}
558Morse code
1lua
k3kh2
import java.util.Random; public class Monty{ public static void main(String[] args){ int switchWins = 0; int stayWins = 0; Random gen = new Random(); for(int plays = 0;plays < 32768;plays++ ){ int[] doors = {0,0,0};
559Monty Hall problem
9java
cwm9h
func multiFactorial(_ n: Int, k: Int) -> Int { return stride(from: n, to: 0, by: -k).reduce(1, *) } let multis = (1...5).map({degree in (1...10).map({member in multiFactorial(member, k: degree) }) }) for (i, degree) in multis.enumerated() { print("Degree \(i + 1): \(degree)") }
552Multifactorial
17swift
ir3o0
<html> <head> <title> n x n Queen solving program </title> </head> <body> <?php echo ; $boardX = $_POST['boardX']; $boardY = $_POST['boardX']; function rotateBoard($p, $boardX) { $a=0; while ($a < count($p)) { $b = strlen(decbin($p[$a]))-1; $tmp[$b] = 1 << ($boardX - $a - 1); ++$a; ...
543N-queens problem
12php
ogv85
sub pi { my $nthrows = shift; my $inside = 0; foreach (1 .. $nthrows) { my $x = rand() * 2 - 1; my $y = rand() * 2 - 1; if (sqrt($x*$x + $y*$y) < 1) { $inside++; } } return 4 * $inside / $nthrows; } printf "%9d:%07f\n", $_, pi($_) for 10**4, 10**6;
557Monte Carlo methods
2perl
4ig5d
function montyhall(tests, doors) { 'use strict'; tests = tests ? tests : 1000; doors = doors ? doors : 3; var prizeDoor, chosenDoor, shownDoor, switchDoor, chosenWins = 0, switchWins = 0;
559Monty Hall problem
10javascript
58vur
<? $loop = 1000000; $count = 0; for ($i=0; $i<$loop; $i++) { $x = rand() / getrandmax(); $y = rand() / getrandmax(); if(($x*$x) + ($y*$y)<=1) $count++; } echo .number_format($loop)..number_format($count)..($count/$loop*4); ?>
557Monte Carlo methods
12php
irnov
>>> def extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return l...
556Modular inverse
3python
k3phf
null
559Monty Hall problem
11kotlin
3btz5
sub F { my $n = shift; $n ? $n - M(F($n-1)) : 1 } sub M { my $n = shift; $n ? $n - F(M($n-1)) : 0 } foreach my $sequence (\&F, \&M) { print join(' ', map $sequence->($_), 0 .. 19), "\n"; }
542Mutual recursion
2perl
u8qvr
function playgame(player) local car = math.random(3) local pchoice = player.choice() local function neither(a, b)
559Monty Hall problem
1lua
6pz39
def extended_gcd(a, b) last_remainder, remainder = a.abs, b.abs x, last_x, y, last_y = 0, 1, 1, 0 while remainder!= 0 last_remainder, (quotient, remainder) = remainder, last_remainder.divmod(remainder) x, last_x = last_x - quotient*x, x y, last_y = last_y - quotient*y, y end return last_remainder...
556Modular inverse
14ruby
pyabh
>>> import random, math >>> throws = 1000 >>> 4.0 * sum(math.hypot(*[random.random()*2-1 for q in [0,1]]) < 1 for p in xrange(throws)) / float(throws) 3.1520000000000001 >>> throws = 1000000 >>> 4.0 * sum(math.hypot(*[random.random()*2-1 for q in [0,1]]) < 1 ...
557Monte Carlo methods
3python
gnr4h
fn mod_inv(a: isize, module: isize) -> isize { let mut mn = (module, a); let mut xy = (0, 1); while mn.1!= 0 { xy = (xy.1, xy.0 - (mn.0 / mn.1) * xy.1); mn = (mn.1, mn.0% mn.1); } while xy.0 < 0 { xy.0 += module; } xy.0 } fn main() { println!("{}", mod_inv(42, 2017)) }
556Modular inverse
15rust
1mepu
def gcdExt(u: Int, v: Int): (Int, Int, Int) = { @tailrec def aux(a: Int, b: Int, x: Int, y: Int, x1: Int, x2: Int, y1: Int, y2: Int): (Int, Int, Int) = { if(b == 0) (x, y, a) else { val (q, r) = (a / b, a % b) aux(b, r, x2 - q * x1, y2 - q * y1, x, x1, y, y1) } } aux(u, v, 1, 0, 0, 1, 1, 0) ...
556Modular inverse
16scala
wlqes
<?php function F($n) { if ( $n == 0 ) return 1; return $n - M(F($n-1)); } function M($n) { if ( $n == 0) return 0; return $n - F(M($n-1)); } $ra = array(); $rb = array(); for($i=0; $i < 20; $i++) { array_push($ra, F($i)); array_push($rb, M($i)); } echo implode(, $ra) . ; echo implode(, $rb) . ; ?>
542Mutual recursion
12php
84v0m
monteCarloPi <- function(samples) { x <- runif(samples, -1, 1) y <- runif(samples, -1, 1) l <- sqrt(x*x + y*y) return(4*sum(l<=1)/samples) } monteCarlo2Pi <- function(samples, group=100) { lim <- ceiling(samples/group) olim <- lim c <- 0 while(lim > 0) { x <- runif(group, -1, 1) y <- runif(g...
557Monte Carlo methods
13r
v0u27
extension BinaryInteger { @inlinable public func modInv(_ mod: Self) -> Self { var (m, n) = (mod, self) var (x, y) = (Self(0), Self(1)) while n!= 0 { (x, y) = (y, x - (m / n) * y) (m, n) = (n, m% n) } while x < 0 { x += mod } return x } } print(42.modInv(2017))
556Modular inverse
17swift
b61kd
use Acme::AGMorse qw(SetMorseVals SendMorseMsg); SetMorseVals(20,30,400); SendMorseMsg('Hello World! abcdefg @\;'); exit;
558Morse code
2perl
zbztb
def approx_pi(throws) times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0} 4.0 * times_inside / throws end [1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n| puts % [n, approx_pi(n)] end
557Monte Carlo methods
14ruby
7fjri
null
556Modular inverse
20typescript
djtn0
extern crate rand; use rand::Rng; use std::f64::consts::PI;
557Monte Carlo methods
15rust
jth72
object MonteCarlo { private val random = new scala.util.Random def nextThrow: Double = (random.nextDouble * 2.0) - 1.0 def insideCircle(pt: (Double, Double)): Boolean = pt match { case (x, y) => (x * x) + (y * y) <= 1.0 } def simulate(times: Int): Double = { val inside = Iterator.tabulate ...
557Monte Carlo methods
16scala
b6pk6
from itertools import permutations n = 8 cols = range(n) for vec in permutations(cols): if n == len(set(vec[i]+i for i in cols)) \ == len(set(vec[i]-i for i in cols)): print ( vec )
543N-queens problem
3python
4is5k
use strict; my $trials = 10000; my $stay = 0; my $switch = 0; foreach (1 .. $trials) { my $prize = int(rand 3); my $chosen = int(rand 3); my $show; do { $show = int(rand 3) } while $show == $chosen || $show == $prize; $stay++ if $prize == $chosen; $switch++ if $prize == 3 - ...
559Monty Hall problem
2perl
p6kb0
package main import ( "fmt" ) func main() { fmt.Print(" x |") for i := 1; i <= 12; i++ { fmt.Printf("%4d", i) } fmt.Print("\n---+") for i := 1; i <= 12; i++ { fmt.Print("----") } for j := 1; j <= 12; j++ { fmt.Printf("\n%2d |", j) for i := 1; i <= 12; i+...
560Multiplication tables
0go
ma3yi
import Foundation func mcpi(sampleSize size:Int) -> Double { var x = 0 as Double var y = 0 as Double var m = 0 as Double for i in 0..<size { x = Double(arc4random()) / Double(UINT32_MAX) y = Double(arc4random()) / Double(UINT32_MAX) if ((x * x) + (y * y) < 1) { m +...
557Monte Carlo methods
17swift
rd7gg
def printMultTable = { size = 12 -> assert size > 1
560Multiplication tables
7groovy
thnfh
queens <- function(n) { a <- seq(n) u <- rep(T, 2 * n - 1) v <- rep(T, 2 * n - 1) m <- NULL aux <- function(i) { if (i > n) { m <<- cbind(m, a) } else { for (j in seq(i, n)) { k <- a[[j]] p <- i - k + n q <- i + k - 1 if (u[[p]] && v[[q]]) { u[[p]]...
543N-queens problem
13r
2selg
<?php function montyhall($iterations){ $switch_win = 0; $stay_win = 0; foreach (range(1, $iterations) as $i){ $doors = array(0, 0, 0); $doors[array_rand($doors)] = 1; $choice = array_rand($doors); do { $shown = array_rand($doors); } while($shown == $choice || $doors[$shown] == 1); $stay_win += $door...
559Monty Hall problem
12php
y1361
def F(n): return 1 if n == 0 else n - M(F(n-1)) def M(n): return 0 if n == 0 else n - F(M(n-1)) print ([ F(n) for n in range(20) ]) print ([ M(n) for n in range(20) ])
542Mutual recursion
3python
5osux
import time, winsound char2morse = { : , .-..-.$...-..-'.----.(-.--.)-.--.-+.-.-.,--..----....-..-.-.-/-..-.0-----1.----2..---3...--4....-5.....6-....7--...8---..9----.:---...;-.-.-.=-...-?..--..@.--.-.A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.O---P.--.Q--.-R.-.S...T-U..-V...-W....
558Morse code
3python
3p3zc
import Data.Maybe (fromMaybe, maybe) mulTable :: [Int] -> [[Maybe Int]] mulTable xs = (Nothing: labels): zipWith (:) labels [[upperMul x y | y <- xs] | x <- xs] where labels = Just <$> xs upperMul x y | x > y = Nothing | otherwise = Just (x * y) main :: IO () main = putStrL...
560Multiplication tables
8haskell
kz7h0
F <- function(n) ifelse(n == 0, 1, n - M(F(n-1))) M <- function(n) ifelse(n == 0, 0, n - F(M(n-1)))
542Mutual recursion
13r
lqece
def n_queens(n) if n == 1 return elsif n < 4 puts return end evens = (2..n).step(2).to_a odds = (1..n).step(2).to_a rem = n % 12 nums = evens nums.rotate if rem == 3 or rem == 9 if rem == 8 odds = odds.each_slice(2).flat_map(&:reverse) end nums.concat(odds) if...
543N-queens problem
14ruby
rd8gs
require 'win32/sound' class MorseCode MORSE = { => , .-..-.$...-..-'.----.(-.--.)-.--.-+.-.-.,--..----....-..-.-.-/-..-.0-----1.----2..---3...--4....-5.....6-....7--...8---..9----.:---...;-.-.-.=-...-?..--..@.--.-.A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-....
558Morse code
14ruby
yay6n
''' I could understand the explanation of the Monty Hall problem but needed some more evidence References: http: http: http: ''' from random import randrange doors, iterations = 3,100000 def monty_hall(choice, switch=False, doorCount=doors): door = [False]*doorCount door[randrange(doorCount)] = Tru...
559Monty Hall problem
3python
1ybpc
public class MultiplicationTable { public static void main(String[] args) { for (int i = 1; i <= 12; i++) System.out.print("\t" + i); System.out.println(); for (int i = 0; i < 100; i++) System.out.print("-"); System.out.println(); for (int i = 1; i <=...
560Multiplication tables
9java
4ov58
null
558Morse code
15rust
memya
<!DOCTYPE html PUBLIC "-
560Multiplication tables
10javascript
htrjh
const N: usize = 8; fn try(mut board: &mut [[bool; N]; N], row: usize, mut count: &mut i64) { if row == N { *count += 1; for r in board.iter() { println!("{}", r.iter().map(|&x| if x {"x"} else {"."}.to_string()).collect::<Vec<String>>().join(" ")) } println!(""); retur...
543N-queens problem
15rust
7forc
def F(n) n == 0? 1: n - M(F(n-1)) end def M(n) n == 0? 0: n - F(M(n-1)) end p (Array.new(20) {|n| F(n) }) p (Array.new(20) {|n| M(n) })
542Mutual recursion
14ruby
gn84q
object MorseCode extends App { private val code = Map( ('A', ".- "), ('B', "-... "), ('C', "-.-. "), ('D', "-.. "), ('E', ". "), ('F', "..-. "), ('G', "--. "), ('H', ".... "), ('I', ".. "), ('J', ".--- "), ('K', "-.- "), ('L', ".-.. "), ('M', "-- "), ('N', "-. ...
558Morse code
16scala
lqlcq
set.seed(19771025) N <- 10000 true_answers <- sample(1:3, N, replace=TRUE) host_opens <- 2 + (true_answers == 2) other_door <- 2 + (true_answers != 2) summary( other_door == true_answers ) summary( true_answers == 1) random_switch <- other_door random_switch[runif(N) >= .5] <- 1 summary(random_switch...
559Monty Hall problem
13r
ht7jj
object NQueens { private implicit class RichPair[T]( pair: (T,T))( implicit num: Numeric[T] ) { import num._ def safe(x: T, y: T): Boolean = pair._1 - pair._2 != abs(x - y) } def solve(n: Int): Iterator[Seq[Int]] = { (0 to n-1) .permutations .filter { v => (0 to ...
543N-queens problem
16scala
k3dhk
fn f(n: u32) -> u32 { match n { 0 => 1, _ => n - m(f(n - 1)) } } fn m(n: u32) -> u32 { match n { 0 => 0, _ => n - f(m(n - 1)) } } fn main() { for i in (0..20).map(f) { print!("{} ", i); } println!(""); for i in (0..20).map(m) { print!("{...
542Mutual recursion
15rust
rdog5
null
560Multiplication tables
11kotlin
lxmcp
n = 10_000 stay = switch = 0 n.times do doors = [ :goat, :goat, :car ].shuffle guess = rand(3) begin shown = rand(3) end while shown == guess || doors[shown] == :car if doors[guess] == :car stay += 1 else switch += 1 end end p...
559Monty Hall problem
14ruby
e91ax
def F(n:Int):Int = if (n == 0) 1 else n - M(F(n-1)) def M(n:Int):Int = if (n == 0) 0 else n - F(M(n-1)) println((0 until 20).map(F).mkString(", ")) println((0 until 20).map(M).mkString(", "))
542Mutual recursion
16scala
hzdja
extern crate rand; use rand::Rng; use rand::seq::SliceRandom; #[derive(Clone, Copy, PartialEq)] enum Prize {Goat , Car} const GAMES: usize = 3_000_000; fn main() { let mut switch_wins = 0; let mut rng = rand::thread_rng(); for _ in 0..GAMES { let mut doors = [Prize::Goat; 3]; *doors.choos...
559Monty Hall problem
15rust
wcae4
import scala.util.Random object MontyHallSimulation { def main(args: Array[String]) { val samples = if (args.size == 1 && (args(0) matches "\\d+")) args(0).toInt else 1000 val doors = Set(0, 1, 2) var stayStrategyWins = 0 var switchStrategyWins = 0 1 to samples foreach { _ => val prizeDoor...
559Monty Hall problem
16scala
svxqo
io.write( " |" ) for i = 1, 12 do io.write( string.format( "%#5d", i ) ) end io.write( "\n", string.rep( "-", 12*5+4 ), "\n" ) for i = 1, 12 do io.write( string.format( "%#2d |", i ) ) for j = 1, 12 do if j < i then io.write( " " ) else io.write( string.format...
560Multiplication tables
1lua
2q9l3
WITH RECURSIVE positions(i) AS ( VALUES(0) UNION SELECT ALL i+1 FROM positions WHERE i < 63 ), solutions(board, n_queens) AS ( SELECT '----------------------------------------------------------------', CAST(0 AS BIGINT) FROM positions UNION SELECT substr(board, 1, i) || '*' ...
543N-queens problem
19sql
1mzpg
package main import ( "fmt" "math" ) const MAXITER = 151 func minkowski(x float64) float64 { if x > 1 || x < 0 { return math.Floor(x) + minkowski(x-math.Floor(x)) } p := uint64(x) q := uint64(1) r := p + 1 s := uint64(1) d := 1.0 y := float64(p) for { d = d...
561Minkowski question-mark function
0go
giv4n
unsigned digit_sum(unsigned n) { unsigned sum = 0; do { sum += n % 10; } while(n /= 10); return sum; } unsigned a131382(unsigned n) { unsigned m; for (m = 1; n != digit_sum(m*n); m++); return m; } int main() { unsigned n; for (n = 1; n <= 70; n++) { printf(, a131382(n)); ...
562Minimum multiple of m where digital sum equals m
5c
vsm2o
import Data.Tree import Data.Ratio import Data.List intervalTree :: (a -> a -> a) -> (a, a) -> Tree a intervalTree node = unfoldTree $ \(a, b) -> let m = node a b in (m, [(a,m), (m,b)]) Node a _ ==> Node b [] = const b Node a [] ==> Node b _ = const b Node a [l1, r1] ==> Node b [l2, r2] = \x -> case x `compare` a...
561Minkowski question-mark function
8haskell
sveqk
import Foundation func montyHall(doors: Int = 3, guess: Int, switch: Bool) -> Bool { guard doors > 2, guess > 0, guess <= doors else { fatalError() } let winningDoor = Int.random(in: 1...doors) return winningDoor == guess?!`switch`: `switch` } var switchResults = [Bool]() for _ in 0..<1_000 { let guess = I...
559Monty Hall problem
17swift
amp1i
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } func commatize(n int) string { s :=...
563Modified random distribution
0go
e9ha6
import System.Random import Data.List import Text.Printf modify :: Ord a => (a -> a) -> [a] -> [a] modify f = foldMap test . pairs where pairs lst = zip lst (tail lst) test (r1, r2) = if r2 < f r1 then [r1] else [] vShape x = if x < 0.5 then 2*(0.5-x) else 2*(x-0.5) hist b lst = zip [0,b..] res where ...
563Modified random distribution
8haskell
3bizj
struct ModularArithmetic { int value; int modulus; }; struct ModularArithmetic make(const int value, const int modulus) { struct ModularArithmetic r = { value % modulus, modulus }; return r; } struct ModularArithmetic add(const struct ModularArithmetic a, const struct ModularArithmetic b) { return...
564Modular arithmetic
5c
madys
let maxn = 31 func nq(n: Int) -> Int { var cols = Array(repeating: 0, count: maxn) var diagl = Array(repeating: 0, count: maxn) var diagr = Array(repeating: 0, count: maxn) var posibs = Array(repeating: 0, count: maxn) var num = 0 for q0 in 0...n-3 { for q1 in q0+2...n-1 { let bi...
543N-queens problem
17swift
gn049
use strict; use warnings; use feature 'say'; use POSIX qw(floor); my $MAXITER = 50; sub minkowski { my($x) = @_; return floor($x) + minkowski( $x - floor($x) ) if $x > 1 || $x < 0 ; my $y = my $p = floor($x); my ($q,$s,$d) = (1,1,1); my $r = $p + 1; while () { last if ( $y + ($d /= ...
561Minkowski question-mark function
2perl
thifg
func F(n: Int) -> Int { return n == 0? 1: n - M(F(n-1)) } func M(n: Int) -> Int { return n == 0? 0: n - F(M(n-1)) } for i in 0..20 { print("\(F(i)) ") } println() for i in 0..20 { print("\(M(i)) ") } println()
542Mutual recursion
17swift
4i05g
use strict; use warnings; use List::Util 'max'; sub distribution { my %param = ( function => \&{scalar sub {return 1}}, sample_size => 1e5, @_); my @values; do { my($r1, $r2) = (rand, rand); push @values, $r1 if &{$param{function}}($r1) > $r2; } until @values == $param{sample_size}; ...
563Modified random distribution
2perl
vsy20
package main import ( "fmt" "strings" ) const limit = 50000 var ( divs, subs []int mins [][]string )
565Minimal steps down to 1
0go
o4a8q
import random from typing import List, Callable, Optional def modifier(x: float) -> float: return 2*(.5 - x) if x < 0.5 else 2*(x - .5) def modified_random_distribution(modifier: Callable[[float], float], n: int) -> List[float]: d: List[float] = [] while len(d)...
563Modified random distribution
3python
u0mvd
import Data.List import Data.Ord import Data.Function (on) data Memo a = Node a (Memo a) (Memo a) deriving Functor memo :: Integral a => Memo p -> a -> p memo (Node a l r) n | n == 0 = a | odd n = memo l (n `div` 2) | otherwise = memo r (n `div` 2 - 1) nats :: Integral a => Memo a nats = Node 0 ((+1).(*2)...
565Minimal steps down to 1
8haskell
2qzll
import math MAXITER = 151 def minkowski(x): if x > 1 or x < 0: return math.floor(x) + minkowski(x - math.floor(x)) p = int(x) q = 1 r = p + 1 s = 1 d = 1.0 y = float(p) while True: d /= 2 if y + d == y: break m = p + r if m < 0 or...
561Minkowski question-mark function
3python
zkntt
library(NostalgiR) modifier <- function(x) 2*abs(x - 0.5) gen <- function() { repeat { random <- runif(2) if(random[2] < modifier(random[1])) return(random[1]) } } data <- replicate(100000, gen()) NostalgiR::nos.hist(data, breaks = 20, pch = "
563Modified random distribution
13r
cwz95
int main() { mpz_t a, b, m, r; mpz_init_set_str(a, , 0); mpz_init_set_str(b, , 0); mpz_init(m); mpz_ui_pow_ui(m, 10, 40); mpz_init(r); mpz_powm(r, a, b, m); gmp_printf(, r); mpz_clear(a); mpz_clear(b); mpz_clear(m); mpz_clear(r); return 0; }
566Modular exponentiation
5c
586uk
package main import "rcu" func main() { var res []int for n := 1; n <= 70; n++ { m := 1 for rcu.DigitSum(m*n, 10) != n { m++ } res = append(res, m) } rcu.PrintTable(res, 7, 10, true) }
562Minimum multiple of m where digital sum equals m
0go
svaqa
import Data.Bifunctor (first) import Data.List (elemIndex, intercalate, transpose) import Data.List.Split (chunksOf) import Data.Maybe (fromJust) import Text.Printf (printf) a131382 :: [Int] a131382 = fromJust . (elemIndex <*> productDigitSums) <$> [1 ..] productDigitSums :: Int -> [Int] productDigitSums n = ...
562Minimum multiple of m where digital sum equals m
8haskell
9ezmo
(defn powerMod "modular exponentiation" [b e m] (defn m* [p q] (mod (* p q) m)) (loop [b b, e e, x 1] (if (zero? e) x (if (even? e) (recur (m* b b) (/ e 2) x) (recur (m* b b) (quot e 2) (m* b x))))))
566Modular exponentiation
6clojure
jfl7m
package main import "fmt"
564Modular arithmetic
0go
am71f
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MinimalStepsDownToOne { public static void main(String[] args) { runTasks(getFunctions1()); runTasks(getFunctions2()); runTasks(getFunctions3()); } private static void r...
565Minimal steps down to 1
9java
6po3z
__int128 imax(__int128 a, __int128 b) { if (a > b) { return a; } return b; } __int128 ipow(__int128 b, __int128 n) { __int128 res; if (n == 0) { return 1; } if (n == 1) { return b; } res = b; while (n > 1) { res *= b; n--; } return...
567Minimum positive multiple in base 10 using only 0 and 1
5c
q2jxc
import Data.Modular f :: /13 -> /13 f x = x^100 + x + 1 main :: IO () main = print (f 10)
564Modular arithmetic
8haskell
zk8t0
public class ModularArithmetic { private interface Ring<T> { Ring<T> plus(Ring<T> rhs); Ring<T> times(Ring<T> rhs); int value(); Ring<T> one(); default Ring<T> pow(int p) { if (p < 0) { throw new IllegalArgumentException("p must be zero or grea...
564Modular arithmetic
9java
o4e8d
use strict; use warnings; use ntheory qw( sumdigits ); my @answers = map { my $m = 1; $m++ until sumdigits($m*$_) == $_; $m; } 1 .. 70; print "@answers\n\n" =~ s/.{65}\K /\n/gr;
562Minimum multiple of m where digital sum equals m
2perl
gi24e
use strict; use warnings; no warnings 'recursion'; use List::Util qw( first ); use Data::Dump 'dd'; for ( [ 2000, [2, 3], [1] ], [ 2000, [2, 3], [2] ] ) { my ( $n, $div, $sub ) = @$_; print "\n", '-' x 40, " divisors @$div subtractors @$sub\n"; my ($solve, $max) = minimal( @$_ ); printf "%4d takes%s step(s)...
565Minimal steps down to 1
2perl
jf27f
null
564Modular arithmetic
11kotlin
xlkws
'''A131382''' from itertools import count, islice def a131382(): '''An infinite series of the terms of A131382''' return ( elemIndex(x)( productDigitSums(x) ) for x in count(1) ) def productDigitSums(n): '''The sum of the decimal digits of n''' return (digitSum(n *...
562Minimum multiple of m where digital sum equals m
3python
rnvgq
from functools import lru_cache DIVS = {2, 3} SUBS = {1} class Minrec(): def __init__(self, divs=DIVS, subs=SUBS): self.divs, self.subs = divs, subs @lru_cache(maxsize=None) def _minrec(self, n): if n == 1: return 0, ['=1'] possibles = {} for ...
565Minimal steps down to 1
3python
htvjw
function make(value, modulo) local v = value % modulo local tbl = {value=v, modulo=modulo} local mt = { __add = function(lhs, rhs) if type(lhs) == "table" then if type(rhs) == "table" then if lhs.modulo ~= rhs.modulo then error...
564Modular arithmetic
1lua
q2bx0
our $max = 12; our $width = length($max**2) + 1; printf "%*s", $width, $_ foreach 'x|', 1..$max; print "\n", '-' x ($width - 1), '+', '-' x ($max*$width), "\n"; foreach my $i (1..$max) { printf "%*s", $width, $_ foreach "$i|", map { $_ >= $i and $_*$i } 1..$max; print "\n"; }
560Multiplication tables
2perl
q2ex6
import Foundation func digitSum(_ num: Int) -> Int { var sum = 0 var n = num while n > 0 { sum += n% 10 n /= 10 } return sum } for n in 1...70 { for m in 1... { if digitSum(m * n) == n { print(String(format: "%8d", m), terminator: n% 10 == 0? "\n": " ") ...
562Minimum multiple of m where digital sum equals m
17swift
7durq
func minToOne(divs: [Int], subs: [Int], upTo n: Int) -> ([Int], [[String]]) { var table = Array(repeating: n + 2, count: n + 1) var how = Array(repeating: [""], count: n + 2) table[1] = 0 how[1] = ["="] for t in 1..<n { let thisPlus1 = table[t] + 1 for div in divs { let dt = div * t if...
565Minimal steps down to 1
17swift
kzuhx
Unix build: make CPPFLAGS=-DNDEBUG LDLIBS=-lcurses mines dwlmines, by David Lambert; sometime in the twentieth Century. The program is meant to run in a terminal window compatible with curses if unix is defined to cpp, or to an ANSI terminal when compiled without unix macro defined. I suppose I...
568Minesweeper game
5c
3bqza
use Math::ModInt qw(mod); sub f { my $x = shift; $x**100 + $x + 1 }; print f mod(10, 13);
564Modular arithmetic
2perl
2q3lf
package main import ( "fmt" "github.com/shabbyrobe/go-num" "strings" "time" ) func b10(n int64) { if n == 1 { fmt.Printf("%4d:%28s %-24d\n", 1, "1", 1) return } n1 := n + 1 pow := make([]int64, n1) val := make([]int64, n1) var count, ten, x int64 = 0, 1, 1 f...
567Minimum positive multiple in base 10 using only 0 and 1
0go
2qfl7
typedef uint8_t card_t; unsigned int rand_n(unsigned int n) { unsigned int out, mask = 1; while (mask < n) mask = mask<<1 | 1; do { out = rand() & mask; } while (out >= n); return out; } card_t rand_card() { return rand_n(52); } void print_card(card_t card) { static c...
569Mind boggling card trick
5c
rn6g7
import Data.Bifunctor (bimap) import Data.List (find) import Data.Maybe (isJust) b10 :: Integral a => a -> Integer b10 n = read (digitMatch rems sums) :: Integer where (_, rems, _, Just (_, sums)) = until (\(_, _, _, mb) -> isJust mb) ( \(e, rems, ms, _) -> let m = rem (10 ^ e...
567Minimum positive multiple in base 10 using only 0 and 1
8haskell
am41g
package main import ( "fmt" "math/big" ) func main() { a, _ := new(big.Int).SetString( "2988348162058574136915891421498819466320163312926952423791023078876139", 10) b, _ := new(big.Int).SetString( "2351399303373464486466122544523690094744975233415544072992656881240319", 10) m := bi...
566Modular exponentiation
0go
85p0g
sem_t sem; int count = 3; void acquire() { sem_wait(&sem); count--; } void release() { count++; sem_post(&sem); } void* work(void * id) { int i = 10; while (i--) { acquire(); printf(, *(int*)id, getcount()); usleep(rand() % 4000000); release(); usleep(0); } return 0; } int main() { pthread_t...
570Metered concurrency
5c
85j04
bool Contains(int lst[], int item, int size) { for (int i = size - 1; i >= 0; i--) if (item == lst[i]) return true; return false; } int * MianChowla() { static int mc[n]; mc[0] = 1; int sums[nn]; sums[0] = 2; int sum, le, ss = 1; for (int i = 1; i < n; i++) { le = ss; for (int j = mc[i - 1] + 1; ; j++) { ...
571Mian-Chowla sequence
5c
svgq5
println 2988348162058574136915891421498819466320163312926952423791023078876139.modPow( 2351399303373464486466122544523690094744975233415544072992656881240319, 10000000000000000000000000000000000000000)
566Modular exponentiation
7groovy
wc7el
modPow :: Integer -> Integer -> Integer -> Integer -> Integer modPow b e 1 r = 0 modPow b 0 m r = r modPow b e m r | e `mod` 2 == 1 = modPow b' e' m (r * b `mod` m) | otherwise = modPow b' e' m r where b' = b * b `mod` m e' = e `div` 2 main = do print (modPow 2988348162058574136915891421498819466320163...
566Modular exponentiation
8haskell
lxfch
import operator import functools @functools.total_ordering class Mod: __slots__ = ['val','mod'] def __init__(self, val, mod): if not isinstance(val, int): raise ValueError('Value must be integer') if not isinstance(mod, int) or mod<=0: raise ValueError('Modulo must be p...
564Modular arithmetic
3python
vs629