code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
import Data.List (unfoldr, genericIndex)
import Control.Monad (replicateM, foldM, mzero)
isEsthetic b = all ((== 1) . abs) . differences . toBase b
where
differences lst = zipWith (-) lst (tail lst)
esthetics_m b =
do differences <- (\n -> replicateM n [-1, 1]) <$> [0..]
firstDigit <- [1..b-1]
differences >>= fromBase b <$> scanl (+) firstDigit
esthetics b = tail $ fst <$> iterate step (undefined, q)
where
q = [(d, d) | d <- [1..b-1]]
step (_, queue) =
let (num, lsd) = head queue
new_lsds = [d | d <- [lsd-1, lsd+1], d < b, d >= 0]
in (num, tail queue ++ [(num*b + d, d) | d <- new_lsds])
fromBase b = foldM f 0
where f r d | d < 0 || d >= b = mzero
| otherwise = pure (r*b + d)
toBase b = reverse . unfoldr f
where
f 0 = Nothing
f n = let (q, r) = divMod n b in Just (r, q)
showInBase b = foldMap (pure . digit) . toBase b
where digit = genericIndex (['0'..'9'] <> ['a'..'z']) | 887Esthetic numbers
| 8haskell
| 3uazj |
dsolveBy _ _ [] _ = error "empty solution interval"
dsolveBy method f mesh x0 = zip mesh results
where results = scanl (method f) x0 intervals
intervals = zip mesh (tail mesh) | 886Euler method
| 8haskell
| 9rsmo |
static unsigned long gcd_ui(unsigned long x, unsigned long y) {
unsigned long t;
if (y < x) { t = x; x = y; y = t; }
while (y > 0) {
t = y; y = x % y; x = t;
}
return x;
}
unsigned long binomial(unsigned long n, unsigned long k) {
unsigned long d, g, r = 1;
if (k == 0) return 1;
if (k == 1) return n;
if (k >= n) return (k == n);
if (k > n/2) k = n-k;
for (d = 1; d <= k; d++) {
if (r >= ULONG_MAX/n) {
unsigned long nr, dr;
g = gcd_ui(n, d); nr = n/g; dr = d/g;
g = gcd_ui(r, dr); r = r/g; dr = dr/g;
if (r >= ULONG_MAX/nr) return 0;
r *= nr;
r /= dr;
n--;
} else {
r *= n--;
r /= d;
}
}
return r;
}
int main() {
printf(, binomial(5, 3));
printf(, binomial(40, 19));
printf(, binomial(67, 31));
return 0;
} | 889Evaluate binomial coefficients
| 5c
| 41i5t |
public class Euler {
private static void euler (Callable f, double y0, int a, int b, int h) {
int t = a;
double y = y0;
while (t < b) {
System.out.println ("" + t + " " + y);
t += h;
y += h * f.compute (t, y);
}
System.out.println ("DONE");
}
public static void main (String[] args) {
Callable cooling = new Cooling ();
int[] steps = {2, 5, 10};
for (int stepSize : steps) {
System.out.println ("Step size: " + stepSize);
euler (cooling, 100.0, 0, 100, stepSize);
}
}
} | 886Euler method
| 9java
| t21f9 |
import java.util.ArrayList;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class EstheticNumbers {
interface RecTriConsumer<A, B, C> {
void accept(RecTriConsumer<A, B, C> f, A a, B b, C c);
}
private static boolean isEsthetic(long n, long b) {
if (n == 0) {
return false;
}
var i = n % b;
var n2 = n / b;
while (n2 > 0) {
var j = n2 % b;
if (Math.abs(i - j) != 1) {
return false;
}
n2 /= b;
i = j;
}
return true;
}
private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {
var esths = new ArrayList<Long>();
var dfs = new RecTriConsumer<Long, Long, Long>() {
public void accept(Long n, Long m, Long i) {
accept(this, n, m, i);
}
@Override
public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) {
if (n <= i && i <= m) {
esths.add(i);
}
if (i == 0 || i > m) {
return;
}
var d = i % 10;
var i1 = i * 10 + d - 1;
var i2 = i1 + 2;
if (d == 0) {
f.accept(f, n, m, i2);
} else if (d == 9) {
f.accept(f, n, m, i1);
} else {
f.accept(f, n, m, i1);
f.accept(f, n, m, i2);
}
}
};
LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));
var le = esths.size();
System.out.printf("Base 10:%d esthetic numbers between%d and%d:%n", le, n, m);
if (all) {
for (int i = 0; i < esths.size(); i++) {
System.out.printf("%d ", esths.get(i));
if ((i + 1) % perLine == 0) {
System.out.println();
}
}
} else {
for (int i = 0; i < perLine; i++) {
System.out.printf("%d ", esths.get(i));
}
System.out.println();
System.out.println("............");
for (int i = le - perLine; i < le; i++) {
System.out.printf("%d ", esths.get(i));
}
}
System.out.println();
System.out.println();
}
public static void main(String[] args) {
IntStream.rangeClosed(2, 16).forEach(b -> {
System.out.printf("Base%d:%dth to%dth esthetic numbers:%n", b, 4 * b, 6 * b);
var n = 1L;
var c = 0L;
while (c < 6 * b) {
if (isEsthetic(n, b)) {
c++;
if (c >= 4 * b) {
System.out.printf("%s ", Long.toString(n, b));
}
}
n++;
}
System.out.println();
});
System.out.println(); | 887Esthetic numbers
| 9java
| imjos |
null | 886Euler method
| 10javascript
| mgqyv |
function isEsthetic(inp, base = 10) {
let arr = inp.toString(base).split('');
if (arr.length == 1) return false;
for (let i = 0; i < arr.length; i++)
arr[i] = parseInt(arr[i], base);
for (i = 0; i < arr.length-1; i++)
if (Math.abs(arr[i]-arr[i+1]) !== 1) return false;
return true;
}
function collectEsthetics(base, range) {
let out = [], x;
if (range) {
for (x = range[0]; x < range[1]; x++)
if (isEsthetic(x)) out.push(x);
return out;
} else {
x = 1;
while (out.length < base*6) {
s = x.toString(base);
if (isEsthetic(s, base)) out.push(s.toUpperCase());
x++;
}
return out.slice(base*4);
}
} | 887Esthetic numbers
| 10javascript
| zv1t2 |
(defn binomial-coefficient [n k]
(let [rprod (fn [a b] (reduce * (range a (inc b))))]
(/ (rprod (- n k -1) n) (rprod 1 k)))) | 889Evaluate binomial coefficients
| 6clojure
| hqzjr |
int makehist(char *S,int *hist,int len){
int wherechar[256];
int i,histlen;
histlen=0;
for(i=0;i<256;i++)wherechar[i]=-1;
for(i=0;i<len;i++){
if(wherechar[(int)S[i]]==-1){
wherechar[(int)S[i]]=histlen;
histlen++;
}
hist[wherechar[(int)S[i]]]++;
}
return histlen;
}
double entropy(int *hist,int histlen,int len){
int i;
double H;
H=0;
for(i=0;i<histlen;i++){
H-=(double)hist[i]/len*log2((double)hist[i]/len);
}
return H;
}
int main(void){
char S[MAXLEN];
int len,*hist,histlen;
double H;
FILE *f;
f=fopen(,);
for(len=0;!feof(f);len++)S[len]=fgetc(f);
S[--len]='\0';
hist=(int*)calloc(len,sizeof(int));
histlen=makehist(S,hist,len);
H=entropy(hist,histlen,len);
printf(,H);
return 0;
} | 890Entropy/Narcissist
| 5c
| 5p8uk |
int main() {
puts(getenv());
puts(getenv());
puts(getenv());
return 0;
} | 891Environment variables
| 5c
| qtlxc |
typedef long long mylong;
void compute(int N, char find_only_one_solution)
{ const int M = 30;
int a, b, c, d, e;
mylong s, t, max, *p5 = (mylong*)malloc(sizeof(mylong)*(N+M));
for(s=0; s < N; ++s)
p5[s] = s * s, p5[s] *= p5[s] * s;
for(max = p5[N - 1]; s < (N + M); p5[s++] = max + 1);
for(a = 1; a < N; ++a)
for(b = a + 1; b < N; ++b)
for(c = b + 1; c < N; ++c)
for(d = c + 1, e = d + ((t = p5[a] + p5[b] + p5[c]) % M); ((s = t + p5[d]) <= max); ++d, ++e)
{ for(e -= M; p5[e + M] <= s; e += M);
if(p5[e] == s)
{ printf(, a, b, c, d, e);
if(find_only_one_solution) goto onexit;
}
}
onexit:
free(p5);
}
int main(void)
{
int tm = clock();
compute(250, 0);
printf(, (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC));
return 0;
} | 892Euler's sum of powers conjecture
| 5c
| 3uhza |
null | 886Euler method
| 11kotlin
| oyj8z |
(System/getenv "HOME") | 891Environment variables
| 6clojure
| im4om |
import kotlin.math.abs
fun isEsthetic(n: Long, b: Long): Boolean {
if (n == 0L) {
return false
}
var i = n % b
var n2 = n / b
while (n2 > 0) {
val j = n2 % b
if (abs(i - j) != 1L) {
return false
}
n2 /= b
i = j
}
return true
}
fun listEsths(n: Long, n2: Long, m: Long, m2: Long, perLine: Int, all: Boolean) {
val esths = mutableListOf<Long>()
fun dfs(n: Long, m: Long, i: Long) {
if (i in n..m) {
esths.add(i)
}
if (i == 0L || i > m) {
return
}
val d = i % 10
val i1 = i * 10 + d - 1
val i2 = i1 + 2
when (d) {
0L -> {
dfs(n, m, i2)
}
9L -> {
dfs(n, m, i1)
}
else -> {
dfs(n, m, i1)
dfs(n, m, i2)
}
}
}
for (i in 0L until 10L) {
dfs(n2, m2, i)
}
val le = esths.size
println("Base 10: $le esthetic numbers between $n and $m:")
if (all) {
for (c_esth in esths.withIndex()) {
print("${c_esth.value} ")
if ((c_esth.index + 1) % perLine == 0) {
println()
}
}
println()
} else {
for (i in 0 until perLine) {
print("${esths[i]} ")
}
println()
println("............")
for (i in le - perLine until le) {
print("${esths[i]} ")
}
println()
}
println()
}
fun main() {
for (b in 2..16) {
println("Base $b: ${4 * b}th to ${6 * b}th esthetic numbers:")
var n = 1L
var c = 0L
while (c < 6 * b) {
if (isEsthetic(n, b.toLong())) {
c++
if (c >= 4 * b) {
print("${n.toString(b)} ")
}
}
n++
}
println()
}
println() | 887Esthetic numbers
| 11kotlin
| qt5x1 |
function to(n, b)
local BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n == 0 then
return "0"
end
local ss = ""
while n > 0 do
local idx = (n % b) + 1
n = math.floor(n / b)
ss = ss .. BASE:sub(idx, idx)
end
return string.reverse(ss)
end
function isEsthetic(n, b)
function uabs(a, b)
if a < b then
return b - a
end
return a - b
end
if n == 0 then
return false
end
local i = n % b
n = math.floor(n / b)
while n > 0 do
local j = n % b
if uabs(i, j) ~= 1 then
return false
end
n = math.floor(n / b)
i = j
end
return true
end
function listEsths(n, n2, m, m2, perLine, all)
local esths = {}
function dfs(n, m, i)
if i >= n and i <= m then
table.insert(esths, i)
end
if i == 0 or i > m then
return
end
local d = i % 10
local i1 = 10 * i + d - 1
local i2 = i1 + 2
if d == 0 then
dfs(n, m, i2)
elseif d == 9 then
dfs(n, m, i1)
else
dfs(n, m, i1)
dfs(n, m, i2)
end
end
for i=0,9 do
dfs(n2, m2, i)
end
local le = #esths
print(string.format("Base 10:%s esthetic numbers between%s and%s:", le, math.floor(n), math.floor(m)))
if all then
for c,esth in pairs(esths) do
io.write(esth.." ")
if c % perLine == 0 then
print()
end
end
print()
else
for i=1,perLine do
io.write(esths[i] .. " ")
end
print("\n............")
for i = le - perLine + 1, le do
io.write(esths[i] .. " ")
end
print()
end
print()
end
for b=2,16 do
print(string.format("Base%d:%dth to%dth esthetic numbers:", b, 4 * b, 6 * b))
local n = 1
local c = 0
while c < 6 * b do
if isEsthetic(n, b) then
c = c + 1
if c >= 4 * b then
io.write(to(n, b).." ")
end
end
n = n + 1
end
print()
end
print() | 887Esthetic numbers
| 1lua
| sz4q8 |
T0 = 100
TR = 20
k = 0.07
delta_t = { 2, 5, 10 }
n = 100
NewtonCooling = function( t ) return -k * ( t - TR ) end
function Euler( f, y0, n, h )
local y = y0
for x = 0, n, h do
print( "", x, y )
y = y + h * f( y )
end
end
for i = 1, #delta_t do
print( "delta_t = ", delta_t[i] )
Euler( NewtonCooling, T0, n, delta_t[i] )
end | 886Euler method
| 1lua
| imhot |
(ns test-p.core
(:require [clojure.math.numeric-tower:as math])
(:require [clojure.data.int-map:as i]))
(defn solve-power-sum [max-value max-sols]
" Finds solutions by using method approach of EchoLisp
Large difference is we store a dictionary of all combinations
of y^5 - x^5 with the x, y value so we can simply lookup rather than have to search "
(let [pow5 (mapv #(math/expt % 5) (range 0 (* 4 max-value)))
y5-x3 (into (i/int-map) (for [x (range 1 max-value)
y (range (+ 1 x) (* 4 max-value))]
[(- (get pow5 y) (get pow5 x)) [x y]]))
solutions-found (atom 0)]
(for [x0 (range 1 max-value)
x1 (range 1 x0)
x2 (range 1 x1)
:when (< @solutions-found max-sols)
:let [sum (apply + (map pow5 [x0 x1 x2]))]
:when (contains? y5-x3 sum)]
(do
(swap! solutions-found inc)
(concat [x0 x1 x2] (get y5-x3 sum))))))
(println (into #{} (map sort (solve-power-sum 250 1))))
(println (into #{} (map sort (solve-power-sum 1000 1000)))) | 892Euler's sum of powers conjecture
| 6clojure
| c7a9b |
package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"os"
"runtime"
)
func main() {
_, src, _, _ := runtime.Caller(0)
fmt.Println("Source file entropy:", entropy(src))
fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}
func entropy(file string) float64 {
d, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var f [256]float64
for _, b := range d {
f[b]++
}
hm := 0.
for _, c := range f {
if c > 0 {
hm += c * math.Log2(c)
}
}
l := float64(len(d))
return math.Log2(l) - hm/l
} | 890Entropy/Narcissist
| 0go
| 8650g |
int list[] = {-7, 1, 5, 2, -4, 3, 0};
int eq_idx(int *a, int len, int **ret)
{
int i, sum, s, cnt;
cnt = s = sum = 0;
*ret = malloc(sizeof(int) * len);
for (i = 0; i < len; i++)
sum += a[i];
for (i = 0; i < len; i++) {
if (s * 2 + a[i] == sum) {
(*ret)[cnt] = i;
cnt++;
}
s += a[i];
}
*ret = realloc(*ret, cnt * sizeof(int));
return cnt;
}
int main()
{
int i, cnt, *idx;
cnt = eq_idx(list, sizeof(list) / sizeof(int), &idx);
printf();
for (i = 0; i < cnt; i++)
printf(, idx[i]);
printf();
return 0;
} | 893Equilibrium index
| 5c
| re8g7 |
import qualified Data.ByteString as BS
import Data.List
import System.Environment
(>>>) = flip (.)
main = getArgs >>= head >>> BS.readFile >>= BS.unpack >>> entropy >>> print
entropy = sort >>> group >>> map genericLength >>> normalize >>> map lg >>> sum
where lg c = -c * logBase 2 c
normalize c = let sc = sum c in map (/ sc) c | 890Entropy/Narcissist
| 8haskell
| ljxch |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class EntropyNarcissist {
private static final String FILE_NAME = "src/EntropyNarcissist.java";
public static void main(String[] args) {
System.out.printf("Entropy of file \"%s\" =%.12f.%n", FILE_NAME, getEntropy(FILE_NAME));
}
private static double getEntropy(String fileName) {
Map<Character,Integer> characterCount = new HashMap<>();
int length = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {
int c = 0;
while ( (c = reader.read()) != -1 ) {
characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);
length++;
}
}
catch ( IOException e ) {
throw new RuntimeException(e);
}
double entropy = 0;
for ( char key : characterCount.keySet() ) {
double fraction = (double) characterCount.get(key) / length;
entropy -= fraction * Math.log(fraction);
}
return entropy / Math.log(2);
}
} | 890Entropy/Narcissist
| 9java
| 3ubzg |
enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 }; | 894Enumerations
| 5c
| 86l04 |
null | 895Enforced immutability
| 5c
| szmq5 |
null | 890Entropy/Narcissist
| 11kotlin
| n9rij |
function getFile (filename)
local inFile = io.open(filename, "r")
local fileContent = inFile:read("*all")
inFile:close()
return fileContent
end
function log2 (x) return math.log(x) / math.log(2) end
function entropy (X)
local N, count, sum, i = X:len(), {}, 0
for char = 1, N do
i = X:sub(char, char)
if count[i] then
count[i] = count[i] + 1
else
count[i] = 1
end
end
for n_i, count_i in pairs(count) do
sum = sum + count_i / N * log2(count_i / N)
end
return -sum
end
print(entropy(getFile(arg[0]))) | 890Entropy/Narcissist
| 1lua
| dc7nq |
(def fruits #{:apple:banana:cherry})
(defn fruit? [x] (contains? fruits x))
(def fruit-value (zipmap fruits (iterate inc 1)))
(println (fruit?:apple))
(println (fruit-value:banana)) | 894Enumerations
| 6clojure
| fl4dm |
use 5.020;
use warnings;
use experimental qw(signatures);
use ntheory qw(fromdigits todigitstring);
sub generate_esthetic ($root, $upto, $callback, $base = 10) {
my $v = fromdigits($root, $base);
return if ($v > $upto);
$callback->($v);
my $t = $root->[-1];
__SUB__->([@$root, $t + 1], $upto, $callback, $base) if ($t + 1 < $base);
__SUB__->([@$root, $t - 1], $upto, $callback, $base) if ($t - 1 >= 0);
}
sub between_esthetic ($from, $upto, $base = 10) {
my @list;
foreach my $k (1 .. $base - 1) {
generate_esthetic([$k], $upto,
sub($n) { push(@list, $n) if ($n >= $from) }, $base);
}
sort { $a <=> $b } @list;
}
sub first_n_esthetic ($n, $base = 10) {
for (my $m = $n * $n ; 1 ; $m *= $base) {
my @list = between_esthetic(1, $m, $base);
return @list[0 .. $n - 1] if @list >= $n;
}
}
foreach my $base (2 .. 16) {
say "\n$base-esthetic numbers at indices ${\(4*$base)}..${\(6*$base)}:";
my @list = first_n_esthetic(6 * $base, $base);
say join(' ', map { todigitstring($_, $base) } @list[4*$base-1 .. $
}
say "\nBase 10 esthetic numbers between 1,000 and 9,999:";
for (my @list = between_esthetic(1e3, 1e4) ; @list ;) {
say join(' ', splice(@list, 0, 20));
}
say "\nBase 10 esthetic numbers between 100,000,000 and 130,000,000:";
for (my @list = between_esthetic(1e8, 1.3e8) ; @list ;) {
say join(' ', splice(@list, 0, 9));
} | 887Esthetic numbers
| 2perl
| vko20 |
use strict ;
use warnings ;
use feature 'say' ;
sub log2 {
my $number = shift ;
return log( $number ) / log( 2 ) ;
}
open my $fh , "<" , $ARGV[ 0 ] or die "Can't open $ARGV[ 0 ]$!\n" ;
my %frequencies ;
my $totallength = 0 ;
while ( my $line = <$fh> ) {
chomp $line ;
next if $line =~ /^$/ ;
map { $frequencies{ $_ }++ } split( // , $line ) ;
$totallength += length ( $line ) ;
}
close $fh ;
my $infocontent = 0 ;
for my $letter ( keys %frequencies ) {
my $content = $frequencies{ $letter } / $totallength ;
$infocontent += $content * log2( $content ) ;
}
$infocontent *= -1 ;
say "The information content of the source file is $infocontent!" ; | 890Entropy/Narcissist
| 2perl
| 7wdrh |
user> (def d [1 2 3 4 5])
#'user/d
user> (assoc d 3 7)
[1 2 3 7 5]
user> d
[1 2 3 4 5] | 895Enforced immutability
| 6clojure
| n9vik |
(defn equilibrium [lst]
(loop [acc '(), i 0, left 0, right (apply + lst), lst lst]
(if (empty? lst)
(reverse acc)
(let [[x & xs] lst
right (- right x)
acc (if (= left right) (cons i acc) acc)]
(recur acc (inc i) (+ left x) right xs))))) | 893Equilibrium index
| 6clojure
| b0fkz |
<?php
$h = 0;
$s = file_get_contents(__FILE__);
$l = strlen($s);
foreach ( count_chars($s, 1) as $c )
$h -=
( $c / $l ) *
log( $c / $l, 2 );
echo $h; | 890Entropy/Narcissist
| 12php
| fljdh |
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println(os.Getenv("SHELL"))
} | 891Environment variables
| 0go
| 2hxl7 |
System.getenv().each { property, value -> println "$property = $value"} | 891Environment variables
| 7groovy
| y4p6o |
sub euler_method {
my ($t0, $t1, $k, $step_size) = @_;
my @results = ( [0, $t0] );
for (my $s = $step_size; $s <= 100; $s += $step_size) {
$t0 -= ($t0 - $t1) * $k * $step_size;
push @results, [$s, $t0];
}
return @results;
}
sub analytical {
my ($t0, $t1, $k, $time) = @_;
return ($t0 - $t1) * exp(-$time * $k) + $t1
}
my ($T0, $T1, $k) = (100, 20, .07);
my @r2 = grep { $_->[0] % 10 == 0 } euler_method($T0, $T1, $k, 2);
my @r5 = grep { $_->[0] % 10 == 0 } euler_method($T0, $T1, $k, 5);
my @r10 = grep { $_->[0] % 10 == 0 } euler_method($T0, $T1, $k, 10);
print "Time\t 2 err(%) 5 err(%) 10 err(%) Analytic\n", "-" x 76, "\n";
for (0 .. $
my $an = analytical($T0, $T1, $k, $r2[$_][0]);
printf "%4d\t".("%9.3f" x 7)."\n",
$r2 [$_][0],
$r2 [$_][1], ($r2 [$_][1] / $an) * 100 - 100,
$r5 [$_][1], ($r5 [$_][1] / $an) * 100 - 100,
$r10[$_][1], ($r10[$_][1] / $an) * 100 - 100,
$an;
} | 886Euler method
| 2perl
| gat4e |
import math
from collections import Counter
def entropy(s):
p, lns = Counter(s), float(len(s))
return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
with open(__file__) as f:
b=f.read()
print(entropy(b)) | 890Entropy/Narcissist
| 3python
| jxf7p |
typedef long long int dlong;
typedef struct {
dlong x, y;
} epnt;
typedef struct {
long a, b;
dlong N;
epnt G;
dlong r;
} curve;
typedef struct {
long a, b;
} pair;
const long mxN = 1073741789;
const long mxr = 1073807325;
const long inf = -2147483647;
curve e;
epnt zerO;
int inverr;
long exgcd (long v, long u)
{
register long q, t;
long r = 0, s = 1;
if (v < 0) v += u;
while (v) {
q = u / v;
t = u - q * v;
u = v; v = t;
t = r - q * s;
r = s; s = t;
}
if (u != 1) {
printf (, u);
inverr = 1;
}
return r;
}
static inline dlong modn (dlong a)
{
a %= e.N;
if (a < 0) a += e.N;
return a;
}
dlong modr (dlong a)
{
a %= e.r;
if (a < 0) a += e.r;
return a;
}
long disc (void)
{
dlong c, a = e.a, b = e.b;
c = 4 * modn(a * modn(a * a));
return modn(-16 * (c + 27 * modn(b * b)));
}
int isO (epnt p)
{
return (p.x == inf) && (p.y == 0);
}
int ison (epnt p)
{
long r, s;
if (! isO (p)) {
r = modn(e.b + p.x * modn(e.a + p.x * p.x));
s = modn(p.y * p.y);
}
return (r == s);
}
void padd (epnt *r, epnt p, epnt q)
{
dlong la, t;
if (isO(p)) {*r = q; return;}
if (isO(q)) {*r = p; return;}
if (p.x != q.x) {
t = p.y - q.y;
la = modn(t * exgcd(p.x - q.x, e.N));
}
else
if ((p.y == q.y) && (p.y != 0)) {
t = modn(3 * modn(p.x * p.x) + e.a);
la = modn(t * exgcd (2 * p.y, e.N));
}
else
{*r = zerO; return;}
t = modn(la * la - p.x - q.x);
r->y = modn(la * (p.x - t) - p.y);
r->x = t; if (inverr) *r = zerO;
}
void pmul (epnt *r, epnt p, long k)
{
epnt s = zerO, q = p;
for (; k; k >>= 1) {
if (k & 1) padd(&s, s, q);
if (inverr) {s = zerO; break;}
padd(&q, q, q);
}
*r = s;
}
void pprint (char *f, epnt p)
{
dlong y = p.y;
if (isO (p))
printf (, f);
else {
if (y > e.N - y) y -= e.N;
printf (, f, p.x, y);
}
}
int ellinit (long i[])
{
long a = i[0], b = i[1];
e.N = i[2]; inverr = 0;
if ((e.N < 5) || (e.N > mxN)) return 0;
e.a = modn(a);
e.b = modn(b);
e.G.x = modn(i[3]);
e.G.y = modn(i[4]);
e.r = i[5];
if ((e.r < 5) || (e.r > mxr)) return 0;
printf (, a, b);
printf (, e.N);
pprint (, e.G);
printf (, e.r);
return 1;
}
double rnd(void)
{
return rand() / ((double)RAND_MAX + 1);
}
pair signature (dlong s, long f)
{
long c, d, u, u1;
pair sg;
epnt V;
printf ();
do {
do {
u = 1 + (long)(rnd() * (e.r - 1));
pmul (&V, e.G, u);
c = modr(V.x);
}
while (c == 0);
u1 = exgcd (u, e.r);
d = modr(u1 * (f + modr(s * c)));
}
while (d == 0);
printf (, u);
pprint (, V);
sg.a = c; sg.b = d;
return sg;
}
int verify (epnt W, long f, pair sg)
{
long c = sg.a, d = sg.b;
long t, c1, h1, h2;
dlong h;
epnt V, V2;
t = (c > 0) && (c < e.r);
t &= (d > 0) && (d < e.r);
if (! t) return 0;
printf ();
h = exgcd (d, e.r);
h1 = modr(f * h);
h2 = modr(c * h);
printf (, h1,h2);
pmul (&V, e.G, h1);
pmul (&V2, W, h2);
pprint (, V);
pprint (, V2);
padd (&V, V, V2);
pprint (, V);
if (isO (V)) return 0;
c1 = modr(V.x);
printf (, c1);
return (c1 == c);
}
void ec_dsa (long f, long d)
{
long i, s, t;
pair sg;
epnt W;
t = (disc() == 0);
t |= isO (e.G);
pmul (&W, e.G, e.r);
t |= ! isO (W);
t |= ! ison (e.G);
if (t) goto errmsg;
printf ();
s = 1 + (long)(rnd() * (e.r - 1));
pmul (&W, e.G, s);
printf (, s);
pprint (, W);
t = e.r;
for (i = 1; i < 32; i <<= 1)
t |= t >> i;
while (f > t) f >>= 1;
printf (, f);
sg = signature (s, f);
if (inverr) goto errmsg;
printf (, sg.a, sg.b);
if (d > 0) {
while (d > t) d >>= 1;
f ^= d;
printf (, f);
}
t = verify (W, f, sg);
if (inverr) goto errmsg;
if (t)
printf ();
else
printf ();
return;
errmsg:
printf ();
printf ();
}
void main (void)
{
typedef long eparm[6];
long d, f;
zerO.x = inf; zerO.y = 0;
srand(time(NULL));
eparm *sp, sets[10] = {
{355, 671, 1073741789, 13693, 10088, 1073807281},
{ 0, 7, 67096021, 6580, 779, 16769911},
{ -3, 1, 877073, 0, 1, 878159},
{ 0, 14, 22651, 63, 30, 151},
{ 3, 2, 5, 2, 1, 5},
{ 0, 7, 67096021, 2402, 6067, 33539822},
{ 0, 7, 67096021, 6580, 779, 67079644},
{ 0, 7, 877069, 3, 97123, 877069},
{ 39, 387, 22651, 95, 27, 22651},
};
f = 0x789abcde; d = 0;
for (sp = sets; ; sp++) {
if (ellinit (*sp))
ec_dsa (f, d);
else
break;
}
} | 896Elliptic Curve Digital Signature Algorithm
| 5c
| oyc80 |
import System.Environment
main = do getEnv "HOME" >>= print
getEnvironment >>= print | 891Environment variables
| 8haskell
| aiy1g |
package main
import "fmt"
import "math/big"
func main() {
fmt.Println(new(big.Int).Binomial(5, 3))
fmt.Println(new(big.Int).Binomial(60, 30))
} | 889Evaluate binomial coefficients
| 0go
| oyg8q |
from collections import deque
from itertools import dropwhile, islice, takewhile
from textwrap import wrap
from typing import Iterable, Iterator
Digits = str
def esthetic_nums(base: int) -> Iterator[int]:
queue: deque[tuple[int, int]] = deque()
queue.extendleft((d, d) for d in range(1, base))
while True:
num, lsd = queue.pop()
yield num
new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)
num *= base
queue.extendleft((num + d, d) for d in new_lsds)
def to_digits(num: int, base: int) -> Digits:
digits: list[str] = []
while num:
num, d = divmod(num, base)
digits.append([d])
return .join(reversed(digits)) if digits else
def pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:
joined = .join(it)
lines = wrap(joined, width=width - indent)
for line in lines:
print(f)
print()
def task_2() -> None:
nums: Iterator[int]
for base in range(2, 16 + 1):
start, stop = 4 * base, 6 * base
nums = esthetic_nums(base)
nums = islice(nums, start - 1, stop)
print(
f
f
)
pprint_it(to_digits(num, base) for num in nums)
def task_3(lower: int, upper: int, base: int = 10) -> None:
nums: Iterator[int] = esthetic_nums(base)
nums = dropwhile(lambda num: num < lower, nums)
nums = takewhile(lambda num: num <= upper, nums)
print(
f
f
)
pprint_it(to_digits(num, base) for num in nums)
if __name__ == :
print()
task_2()
print()
task_3(1_000, 9_999)
print()
task_3(100_000_000, 130_000_000) | 887Esthetic numbers
| 3python
| ubivd |
def factorial = { x ->
assert x > -1
x == 0 ? 1: (1..x).inject(1G) { BigInteger product, BigInteger factor -> product *= factor }
}
def combinations = { n, k ->
assert k >= 0
assert n >= k
factorial(n).intdiv(factorial(k)*factorial(n-k))
} | 889Evaluate binomial coefficients
| 7groovy
| xf2wl |
def entropy(s)
counts = s.each_char.tally
size = s.size.to_f
counts.values.reduce(0) do |entropy, count|
freq = count / size
entropy - freq * Math.log2(freq)
end
end
s = File.read(__FILE__)
p entropy(s) | 890Entropy/Narcissist
| 14ruby
| kszhg |
use std::fs::File;
use std::io::{Read, BufReader};
fn entropy<I: IntoIterator<Item = u8>>(iter: I) -> f32 {
let mut histogram = [0u64; 256];
let mut len = 0u64;
for b in iter {
histogram[b as usize] += 1;
len += 1;
}
histogram
.iter()
.cloned()
.filter(|&h| h > 0)
.map(|h| h as f32 / len as f32)
.map(|ratio| -ratio * ratio.log2())
.sum()
}
fn main() {
let name = std::env::args().nth(0).expect("Could not get program name.");
let file = BufReader::new(File::open(name).expect("Could not read file."));
println!("Entropy is {}.", entropy(file.bytes().flatten()));
} | 890Entropy/Narcissist
| 15rust
| b03kx |
typedef struct { double x, y; } pt;
pt zero(void) { return (pt){ INFINITY, INFINITY }; }
int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }
pt neg(pt p) { return (pt){ p.x, -p.y }; }
pt dbl(pt p) {
if (is_zero(p)) return p;
pt r;
double L = (3 * p.x * p.x) / (2 * p.y);
r.x = L * L - 2 * p.x;
r.y = L * (p.x - r.x) - p.y;
return r;
}
pt add(pt p, pt q) {
if (p.x == q.x && p.y == q.y) return dbl(p);
if (is_zero(p)) return q;
if (is_zero(q)) return p;
pt r;
double L = (q.y - p.y) / (q.x - p.x);
r.x = L * L - p.x - q.x;
r.y = L * (p.x - r.x) - p.y;
return r;
}
pt mul(pt p, int n) {
int i;
pt r = zero();
for (i = 1; i <= n; i <<= 1) {
if (i & n) r = add(r, p);
p = dbl(p);
}
return r;
}
void show(const char *s, pt p) {
printf(, s);
printf(is_zero(p) ? : , p.x, p.y);
}
pt from_y(double y) {
pt r;
r.x = pow(y * y - C, 1.0/3);
r.y = y;
return r;
}
int main(void) {
pt a, b, c, d;
a = from_y(1);
b = from_y(2);
show(, a);
show(, b);
show(, c = add(a, b));
show(, d = neg(c));
show(, add(c, d));
show(, add(a, add(b, d)));
show(, mul(a, 12345));
return 0;
} | 897Elliptic curve arithmetic
| 5c
| 1onpj |
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"fmt"
"log"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
check(err)
fmt.Println("Private key:\nD:", priv.D)
pub := priv.Public().(*ecdsa.PublicKey)
fmt.Println("\nPublic key:")
fmt.Println("X:", pub.X)
fmt.Println("Y:", pub.Y)
msg := "Rosetta Code"
fmt.Println("\nMessage:", msg)
hash := sha256.Sum256([]byte(msg)) | 896Elliptic Curve Digital Signature Algorithm
| 0go
| 41w52 |
package main
func main() {
s := "immutable"
s[0] = 'a'
} | 895Enforced immutability
| 0go
| vka2m |
pi = 3.14159
msg = "Hello World" | 895Enforced immutability
| 8haskell
| enzai |
System.getenv("HOME") | 891Environment variables
| 9java
| jxd7c |
var shell = new ActiveXObject("WScript.Shell");
var env = shell.Environment("PROCESS");
WScript.echo('SYSTEMROOT=' + env.item('SYSTEMROOT')); | 891Environment variables
| 10javascript
| 1o6p7 |
typedef unsigned long long ull;
void evolve(ull state, int rule)
{
int i, p, q, b;
for (p = 0; p < 10; p++) {
for (b = 0, q = 8; q--; ) {
ull st = state;
b |= (st&1) << q;
for (state = i = 0; i < N; i++)
if (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))
state |= B(i);
}
printf(, b);
}
putchar('\n');
return;
}
int main(void)
{
evolve(1, 30);
return 0;
} | 898Elementary cellular automaton/Random Number Generator
| 5c
| t2vf4 |
final int immutableInt = 4;
int mutableInt = 4;
mutableInt = 6; | 895Enforced immutability
| 9java
| hqojm |
const pi = 3.1415;
const msg = "Hello World"; | 895Enforced immutability
| 10javascript
| ait10 |
choose :: (Integral a) => a -> a -> a
choose n k = product [k+1..n] `div` product [1..n-k] | 889Evaluate binomial coefficients
| 8haskell
| 2hsll |
const (
apple = iota
banana
cherry
) | 894Enumerations
| 0go
| 5pxul |
enum Fruit { apple, banana, cherry }
enum ValuedFruit {
apple(1), banana(2), cherry(3);
def value
ValuedFruit(val) {value = val}
String toString() { super.toString() + "(${value})" }
}
println Fruit.values()
println ValuedFruit.values() | 894Enumerations
| 7groovy
| c7p9i |
use strict;
use warnings;
use Crypt::EC_DSA;
my $ecdsa = new Crypt::EC_DSA;
my ($pubkey, $prikey) = $ecdsa->keygen;
print "Message: ", my $msg = 'Rosetta Code', "\n";
print "Private Key:\n$prikey \n";
print "Public key :\n", $pubkey->x, "\n", $pubkey->y, "\n";
my $signature = $ecdsa->sign( Message => $msg, Key => $prikey );
print "Signature :\n";
for (sort keys %$signature) { print "$_ => $signature->{$_}\n"; }
$ecdsa->verify( Message => $msg, Key => $pubkey, Signature => $signature ) and
print "Signature verified.\n" | 896Elliptic Curve Digital Signature Algorithm
| 2perl
| flud7 |
int dir_empty(const char *path)
{
struct dirent *ent;
int ret = 1;
DIR *d = opendir(path);
if (!d) {
fprintf(stderr, , path);
perror();
return -1;
}
while ((ent = readdir(d))) {
if (!strcmp(ent->d_name, ) || !(strcmp(ent->d_name, )))
continue;
ret = 0;
break;
}
closedir(d);
return ret;
}
int main(int c, char **v)
{
int ret = 0, i;
if (c < 2) return -1;
for (i = 1; i < c; i++) {
ret = dir_empty(v[i]);
if (ret >= 0)
printf(, v[i], ret ? : );
}
return 0;
} | 899Empty directory
| 5c
| 2hhlo |
null | 895Enforced immutability
| 11kotlin
| 41x57 |
local pi <const> = 3.14159265359 | 895Enforced immutability
| 1lua
| gaq4j |
int makehist(unsigned char *S,int *hist,int len){
int wherechar[256];
int i,histlen;
histlen=0;
for(i=0;i<256;i++)wherechar[i]=-1;
for(i=0;i<len;i++){
if(wherechar[(int)S[i]]==-1){
wherechar[(int)S[i]]=histlen;
histlen++;
}
hist[wherechar[(int)S[i]]]++;
}
return histlen;
}
double entropy(int *hist,int histlen,int len){
int i;
double H;
H=0;
for(i=0;i<histlen;i++){
H-=(double)hist[i]/len*log2((double)hist[i]/len);
}
return H;
}
int main(void){
unsigned char S[MAXLEN];
int len,*hist,histlen;
double H;
scanf(,S);
len=strlen(S);
hist=(int*)calloc(len,sizeof(int));
histlen=makehist(S,hist,len);
H=entropy(hist,histlen,len);
printf(,H);
return 0;
} | 900Entropy
| 5c
| p80by |
void halve(int *x) { *x >>= 1; }
void doublit(int *x) { *x <<= 1; }
bool iseven(const int x) { return (x & 1) == 0; }
int ethiopian(int plier,
int plicand, const bool tutor)
{
int result=0;
if (tutor)
printf(, plier, plicand);
while(plier >= 1) {
if ( iseven(plier) ) {
if (tutor) printf(, plier, plicand);
} else {
if (tutor) printf(, plier, plicand);
result += plicand;
}
halve(&plier); doublit(&plicand);
}
return result;
}
int main()
{
printf(, ethiopian(17, 34, true));
return 0;
} | 901Ethiopian multiplication
| 5c
| wdiec |
null | 891Environment variables
| 11kotlin
| 5p0ua |
if (x & 1) {
} else {
} | 902Even or odd
| 5c
| c749c |
def euler(f,y0,a,b,h):
t,y = a,y0
while t <= b:
print % (t,y)
t += h
y += h * f(t,y)
def newtoncooling(time, temp):
return -0.07 * (temp - 20)
euler(newtoncooling,100,0,100,10) | 886Euler method
| 3python
| rezgq |
euler <- function(f, y0, a, b, h)
{
t <- a
y <- y0
while (t < b)
{
cat(sprintf("%6.3f%6.3f\n", t, y))
t <- t + h
y <- y + h*f(t, y)
}
}
newtoncooling <- function(time, temp){
return(-0.07*(temp-20))
}
euler(newtoncooling, 100, 0, 100, 10) | 886Euler method
| 13r
| ubnvx |
data Fruit = Apple | Banana | Cherry deriving Enum | 894Enumerations
| 8haskell
| xfyw4 |
package main
import "fmt"
const n = 64
func pow2(x uint) uint64 {
return uint64(1) << x
}
func evolve(state uint64, rule int) {
for p := 0; p < 10; p++ {
b := uint64(0)
for q := 7; q >= 0; q-- {
st := state
b |= (st & 1) << uint(q)
state = 0
for i := uint(0); i < n; i++ {
var t1, t2, t3 uint64
if i > 0 {
t1 = st >> (i - 1)
} else {
t1 = st >> 63
}
if i == 0 {
t2 = st << 1
} else if i == 1 {
t2 = st << 63
} else {
t2 = st << (n + 1 - i)
}
t3 = 7 & (t1 | t2)
if (uint64(rule) & pow2(uint(t3))) != 0 {
state |= pow2(i)
}
}
}
fmt.Printf("%d ", b)
}
fmt.Println()
}
func main() {
evolve(1, 30)
} | 898Elementary cellular automaton/Random Number Generator
| 0go
| hqsjq |
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Println(ex([]int32{-7, 1, 5, 2, -4, 3, 0})) | 893Equilibrium index
| 0go
| n95i1 |
def isEsthetic(n, b)
if n == 0 then
return false
end
i = n % b
n2 = (n / b).floor
while n2 > 0
j = n2 % b
if (i - j).abs!= 1 then
return false
end
n2 = n2 / b
i = j
end
return true
end
def listEsths(n, n2, m, m2, perLine, all)
esths = Array.new
dfs = lambda {|n, m, i|
if n <= i and i <= m then
esths << i
end
if i == 0 or i > m then
return
end
d = i % 10
i1 = i * 10 + d - 1
i2 = i1 + 2
if d == 0 then
dfs[n, m, i2]
elsif d == 9 then
dfs[n, m, i1]
else
dfs[n, m, i1]
dfs[n, m, i2]
end
}
for i in 0..9
dfs[n2, m2, i]
end
le = esths.length
print % [le, n, m]
if all then
esths.each_with_index { |esth, idx|
print % [esth]
if (idx + 1) % perLine == 0 then
print
end
}
print
else
for i in 0 .. perLine - 1
print % [esths[i]]
end
print
for i in le - perLine .. le - 1
print % [esths[i]]
end
print
end
print
end
def main
for b in 2..16
print % [b, 4 * b, 6 * b]
n = 1
c = 0
while c < 6 * b
if isEsthetic(n, b) then
c = c + 1
if c >= 4 * b then
print % [n.to_s(b)]
end
end
n = n + 1
end
print
end
print
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(1e8, 101010101, 13 * 1e7, 123456789, 9, true)
listEsths(1e11, 101010101010, 13 * 1e10, 123456789898, 7, false)
listEsths(1e14, 101010101010101, 13 * 1e13, 123456789898989, 5, false)
listEsths(1e17, 101010101010101010, 13 * 1e16, 123456789898989898, 4, false)
end
main() | 887Esthetic numbers
| 14ruby
| 41d5p |
public class Binomial { | 889Evaluate binomial coefficients
| 9java
| 6513z |
package main
import (
"fmt"
"math"
)
const bCoeff = 7
type pt struct{ x, y float64 }
func zero() pt {
return pt{math.Inf(1), math.Inf(1)}
}
func is_zero(p pt) bool {
return p.x > 1e20 || p.x < -1e20
}
func neg(p pt) pt {
return pt{p.x, -p.y}
}
func dbl(p pt) pt {
if is_zero(p) {
return p
}
L := (3 * p.x * p.x) / (2 * p.y)
x := L*L - 2*p.x
return pt{
x: x,
y: L*(p.x-x) - p.y,
}
}
func add(p, q pt) pt {
if p.x == q.x && p.y == q.y {
return dbl(p)
}
if is_zero(p) {
return q
}
if is_zero(q) {
return p
}
L := (q.y - p.y) / (q.x - p.x)
x := L*L - p.x - q.x
return pt{
x: x,
y: L*(p.x-x) - p.y,
}
}
func mul(p pt, n int) pt {
r := zero()
for i := 1; i <= n; i <<= 1 {
if i&n != 0 {
r = add(r, p)
}
p = dbl(p)
}
return r
}
func show(s string, p pt) {
fmt.Printf("%s", s)
if is_zero(p) {
fmt.Println("Zero")
} else {
fmt.Printf("(%.3f,%.3f)\n", p.x, p.y)
}
}
func from_y(y float64) pt {
return pt{
x: math.Cbrt(y*y - bCoeff),
y: y,
}
}
func main() {
a := from_y(1)
b := from_y(2)
show("a = ", a)
show("b = ", b)
c := add(a, b)
show("c = a + b = ", c)
d := neg(c)
show("d = -c = ", d)
show("c + d = ", add(c, d))
show("a + b + d = ", add(a, add(b, d)))
show("a * 12345 = ", mul(a, 12345))
} | 897Elliptic curve arithmetic
| 0go
| y4r64 |
enum Fruits{
APPLE, BANANA, CHERRY
} | 894Enumerations
| 9java
| b0dk3 |
import CellularAutomata (fromList, rule, runCA)
import Control.Comonad
import Data.List (unfoldr)
rnd = fromBits <$> unfoldr (pure . splitAt 8) bits
where
size = 80
bits =
extract
<$> runCA
(rule 30)
(fromList (1: replicate size 0))
fromBits = foldl ((+) . (2 *)) 0 | 898Elementary cellular automaton/Random Number Generator
| 8haskell
| im9or |
null | 898Elementary cellular automaton/Random Number Generator
| 11kotlin
| p8ob6 |
from collections import namedtuple
from hashlib import sha256
from math import ceil, log
from random import randint
from typing import NamedTuple
secp256k1_data = dict(
p=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F,
a=0x0,
b=0x7,
r=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141,
Gx=0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
Gy=0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8,
)
secp256k1 = namedtuple(, secp256k1_data)(**secp256k1_data)
assert (secp256k1.Gy ** 2 - secp256k1.Gx ** 3 - 7)% secp256k1.p == 0
class CurveFP(NamedTuple):
p: int
a: int
b: int
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 lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
def modinv(a, m):
g, x, _ = extended_gcd(a, m)
if g != 1:
raise ValueError
return x% m
class PointEC(NamedTuple):
curve: CurveFP
x: int
y: int
@classmethod
def build(cls, curve, x, y):
x = x% curve.p
y = y% curve.p
rv = cls(curve, x, y)
if not rv.is_identity():
assert rv.in_curve()
return rv
def get_identity(self):
return PointEC.build(self.curve, 0, 0)
def copy(self):
return PointEC.build(self.curve, self.x, self.y)
def __neg__(self):
return PointEC.build(self.curve, self.x, -self.y)
def __sub__(self, Q):
return self + (-Q)
def __equals__(self, Q):
return self.x == Q.x and self.y == Q.y
def is_identity(self):
return self.x == 0 and self.y == 0
def __add__(self, Q):
p = self.curve.p
if self.is_identity():
return Q.copy()
if Q.is_identity():
return self.copy()
if Q.x == self.x and (Q.y == (-self.y% p)):
return self.get_identity()
if self != Q:
l = ((Q.y - self.y) * modinv(Q.x - self.x, p))% p
else:
l = ((3 * self.x ** 2 + self.curve.a) * modinv(2 * self.y, p))% p
l = int(l)
Rx = (l ** 2 - self.x - Q.x)% p
Ry = (l * (self.x - Rx) - self.y)% p
rv = PointEC.build(self.curve, Rx, Ry)
return rv
def in_curve(self):
return ((self.y ** 2)% self.curve.p) == (
(self.x ** 3 + self.curve.a * self.x + self.curve.b)% self.curve.p
)
def __mul__(self, s):
r0 = self.get_identity()
r1 = self.copy()
for i in range(ceil(log(s + 1, 2)) - 1, -1, -1):
if ((s & (1 << i)) >> i) == 0:
r1 = r0 + r1
r0 = r0 + r0
else:
r0 = r0 + r1
r1 = r1 + r1
return r0
def __rmul__(self, other):
return self.__mul__(other)
class ECCSetup(NamedTuple):
E: CurveFP
G: PointEC
r: int
secp256k1_curve = CurveFP(secp256k1.p, secp256k1.a, secp256k1.b)
secp256k1_basepoint = PointEC(secp256k1_curve, secp256k1.Gx, secp256k1.Gy)
class ECDSAPrivKey(NamedTuple):
ecc_setup: ECCSetup
secret: int
def get_pubkey(self):
W = self.secret * self.ecc_setup.G
pub = ECDSAPubKey(self.ecc_setup, W)
return pub
class ECDSAPubKey(NamedTuple):
ecc_setup: ECCSetup
W: PointEC
class ECDSASignature(NamedTuple):
c: int
d: int
def generate_keypair(ecc_setup, s=None):
if s is None:
s = randint(1, ecc_setup.r - 1)
priv = ECDSAPrivKey(ecc_setup, s)
pub = priv.get_pubkey()
return priv, pub
def get_msg_hash(msg):
return int.from_bytes(sha256(msg).digest(), )
def sign(priv, msg, u=None):
G = priv.ecc_setup.G
r = priv.ecc_setup.r
msg_hash = get_msg_hash(msg)
while True:
if u is None:
u = randint(1, r - 1)
V = u * G
c = V.x% r
if c == 0:
print(f)
continue
d = (modinv(u, r) * (msg_hash + priv.secret * c))% r
if d == 0:
print(f)
continue
break
signature = ECDSASignature(c, d)
return signature
def verify_signature(pub, msg, signature):
r = pub.ecc_setup.r
G = pub.ecc_setup.G
c = signature.c
d = signature.d
def num_ok(n):
return 1 < n < (r - 1)
if not num_ok(c):
raise ValueError(f)
if not num_ok(d):
raise ValueError(f)
msg_hash = get_msg_hash(msg)
h = modinv(d, r)
h1 = (msg_hash * h)% r
h2 = (c * h)% r
P = h1 * G + h2 * pub.W
c1 = P.x% r
rv = c1 == c
return rv
def get_ecc_setup(curve=None, basepoint=None, r=None):
if curve is None:
curve = secp256k1_curve
if basepoint is None:
basepoint = secp256k1_basepoint
if r is None:
r = secp256k1.r
E = CurveFP(curve.p, curve.a, curve.b)
G = PointEC(E, basepoint.x, basepoint.y)
assert (G * r) == G.get_identity()
ecc_setup = ECCSetup(E, G, r)
return ecc_setup
def main():
ecc_setup = get_ecc_setup()
print(f)
print(f)
print(f)
print()
priv, pub = generate_keypair(ecc_setup)
print(f)
print(f)
msg_orig = b
signature = sign(priv, msg_orig)
print(f)
validation = verify_signature(pub, msg_orig, signature)
print(f)
msg_bad = b
validation = verify_signature(pub, msg_bad, signature)
print(f)
if __name__ == :
main() | 896Elliptic Curve Digital Signature Algorithm
| 3python
| t25fw |
(require '[clojure.java.io:as io])
(defn empty-dir? [path]
(let [file (io/file path)]
(assert (.exists file))
(assert (.isDirectory file))
(-> file .list empty?))) | 899Empty directory
| 6clojure
| gaa4f |
import System.Random (randomRIO)
import Data.List (findIndices, takeWhile)
import Control.Monad (replicateM)
import Control.Arrow ((&&&))
equilibr xs =
findIndices (\(a, b) -> sum a == sum b) . takeWhile (not . null . snd) $
flip ((&&&) <$> take <*> (drop . pred)) xs <$> [1 ..]
langeSliert = replicateM 2000 (randomRIO (-15, 15) :: IO Int) >>= print . equilibr | 893Equilibrium index
| 8haskell
| ubxv2 |
print( os.getenv( "PATH" ) ) | 891Environment variables
| 1lua
| 4185c |
null | 887Esthetic numbers
| 15rust
| gaf4o |
function binom(n, k) {
var coeff = 1;
var i;
if (k < 0 || k > n) return 0;
for (i = 0; i < k; i++) {
coeff = coeff * (n - i) / (i + 1);
}
return coeff;
}
console.log(binom(5, 3)); | 889Evaluate binomial coefficients
| 10javascript
| ljqcf |
import Data.Monoid
import Control.Monad (guard)
import Test.QuickCheck (quickCheck) | 897Elliptic curve arithmetic
| 8haskell
| hq0ju |
null | 894Enumerations
| 10javascript
| wd6e2 |
use constant PI => 3.14159;
use constant MSG => "Hello World"; | 895Enforced immutability
| 2perl
| im2o3 |
define(, 3.14159265358);
define(, ); | 895Enforced immutability
| 12php
| resge |
(defn entropy [s]
(let [len (count s), log-2 (Math/log 2)]
(->> (frequencies s)
(map (fn [[_ v]]
(let [rf (/ v len)]
(-> (Math/log rf) (/ log-2) (* rf) Math/abs))))
(reduce +)))) | 900Entropy
| 6clojure
| xfdwk |
(defn halve [n]
(bit-shift-right n 1))
(defn twice [n]
(bit-shift-left n 1))
(defn even [n]
(zero? (bit-and n 1)))
(defn emult [x y]
(reduce +
(map second
(filter #(not (even (first %)))
(take-while #(pos? (first %))
(map vector
(iterate halve x)
(iterate twice y)))))))
(defn emult2 [x y]
(loop [a x, b y, r 0]
(if (= a 1)
(+ r b)
(if (even a)
(recur (halve a) (twice b) r)
(recur (halve a) (twice b) (+ r b)))))) | 901Ethiopian multiplication
| 6clojure
| 86z05 |
(if (even? some-var) (do-even-stuff))
(if (odd? some-var) (do-odd-stuff)) | 902Even or odd
| 6clojure
| 5phuz |
def euler(y, a, b, h)
a.step(b,h) do |t|
puts % [t,y]
y += h * yield(t,y)
end
end
[10, 5, 2].each do |step|
puts
euler(100,0,100,step) {|time, temp| -0.07 * (temp - 20) }
puts
end | 886Euler method
| 14ruby
| jx67x |
import static java.lang.Math.*;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
Pt a = Pt.fromY(1);
Pt b = Pt.fromY(2);
System.out.printf("a =%s%n", a);
System.out.printf("b =%s%n", b);
Pt c = a.plus(b);
System.out.printf("c = a + b =%s%n", c);
Pt d = c.neg();
System.out.printf("d = -c =%s%n", d);
System.out.printf("c + d =%s%n", c.plus(d));
System.out.printf("a + b + d =%s%n", a.plus(b).plus(d));
System.out.printf("a * 12345 =%s%n", a.mult(12345));
}
}
class Pt {
final static int bCoeff = 7;
double x, y;
Pt(double x, double y) {
this.x = x;
this.y = y;
}
static Pt zero() {
return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
}
boolean isZero() {
return this.x > 1e20 || this.x < -1e20;
}
static Pt fromY(double y) {
return new Pt(cbrt(pow(y, 2) - bCoeff), y);
}
Pt dbl() {
if (isZero())
return this;
double L = (3 * this.x * this.x) / (2 * this.y);
double x2 = pow(L, 2) - 2 * this.x;
return new Pt(x2, L * (this.x - x2) - this.y);
}
Pt neg() {
return new Pt(this.x, -this.y);
}
Pt plus(Pt q) {
if (this.x == q.x && this.y == q.y)
return dbl();
if (isZero())
return q;
if (q.isZero())
return this;
double L = (q.y - this.y) / (q.x - this.x);
double xx = pow(L, 2) - this.x - q.x;
return new Pt(xx, L * (this.x - xx) - this.y);
}
Pt mult(int n) {
Pt r = Pt.zero();
Pt p = this;
for (int i = 1; i <= n; i <<= 1) {
if ((i & n) != 0)
r = r.plus(p);
p = p.dbl();
}
return r;
}
@Override
public String toString() {
if (isZero())
return "Zero";
return String.format(Locale.US, "(%.3f,%.3f)", this.x, this.y);
}
} | 897Elliptic curve arithmetic
| 9java
| 5pauf |
null | 894Enumerations
| 11kotlin
| re0go |
package Automaton {
sub new {
my $class = shift;
my $rule = [ reverse split //, sprintf "%08b", shift ];
return bless { rule => $rule, cells => [ @_ ] }, $class;
}
sub next {
my $this = shift;
my @previous = @{$this->{cells}};
$this->{cells} = [
@{$this->{rule}}[
map {
4*$previous[($_ - 1) % @previous]
+ 2*$previous[$_]
+ $previous[($_ + 1) % @previous]
} 0 .. @previous - 1
]
];
return $this;
}
use overload
q{""} => sub {
my $this = shift;
join '', map { $_ ? '
};
}
my $a = Automaton->new(30, 1, map 0, 1 .. 100);
for my $n (1 .. 10) {
my $sum = 0;
for my $b (1 .. 8) {
$sum = $sum * 2 + $a->{cells}[0];
$a->next;
}
print $sum, $n == 10 ? "\n" : " ";
} | 898Elementary cellular automaton/Random Number Generator
| 2perl
| y4g6u |
public class Equlibrium {
public static void main(String[] args) {
int[] sequence = {-7, 1, 5, 2, -4, 3, 0};
equlibrium_indices(sequence);
}
public static void equlibrium_indices(int[] sequence){ | 893Equilibrium index
| 9java
| mgbym |
extension Sequence {
func take(_ n: Int) -> [Element] {
var res = [Element]()
for el in self {
guard res.count!= n else {
return res
}
res.append(el)
}
return res
}
}
extension String {
func isEsthetic(base: Int = 10) -> Bool {
zip(dropFirst(0), dropFirst())
.lazy
.allSatisfy({ abs(Int(String($0.0), radix: base)! - Int(String($0.1), radix: base)!) == 1 })
}
}
func getEsthetics(from: Int, to: Int, base: Int = 10) -> [String] {
guard base >= 2, to >= from else {
return []
}
var start = ""
var end = ""
repeat {
if start.count & 1 == 1 {
start += "0"
} else {
start += "1"
}
} while Int(start, radix: base)! < from
let digiMax = String(base - 1, radix: base)
let lessThanDigiMax = String(base - 2, radix: base)
var count = 0
repeat {
if count!= base - 1 {
end += String(count + 1, radix: base)
count += 1
} else {
if String(end.last!) == digiMax {
end += lessThanDigiMax
} else {
end += digiMax
}
}
} while Int(end, radix: base)! < to
if Int(start, radix: base)! >= Int(end, radix: base)! {
return []
}
var esthetics = [Int]()
func shimmer(_ n: Int, _ m: Int, _ i: Int) {
if (n...m).contains(i) {
esthetics.append(i)
} else if i == 0 || i > m {
return
}
let d = i% base
let i1 = i &* base &+ d &- 1
let i2 = i1 &+ 2
if (i1 < i || i2 < i) { | 887Esthetic numbers
| 17swift
| 5pnu8 |
package main
import (
"fmt"
"log"
)
func main() {
fmt.Println(eulerSum())
}
func eulerSum() (x0, x1, x2, x3, y int) {
var pow5 [250]int
for i := range pow5 {
pow5[i] = i * i * i * i * i
}
for x0 = 4; x0 < len(pow5); x0++ {
for x1 = 3; x1 < x0; x1++ {
for x2 = 2; x2 < x1; x2++ {
for x3 = 1; x3 < x2; x3++ {
sum := pow5[x0] +
pow5[x1] +
pow5[x2] +
pow5[x3]
for y = x0 + 1; y < len(pow5); y++ {
if sum == pow5[y] {
return
}
}
}
}
}
}
log.Fatal("no solution")
return
} | 892Euler's sum of powers conjecture
| 0go
| b0tkh |
fn header() {
print!(" Time: ");
for t in (0..100).step_by(10) {
print!(" {:7}", t);
}
println!();
}
fn analytic() {
print!("Analytic: ");
for t in (0..=100).step_by(10) {
print!(" {:7.3}", 20.0 + 80.0 * (-0.07 * f64::from(t)).exp());
}
println!();
}
fn euler<F: Fn(f64) -> f64>(f: F, mut y: f64, step: usize, end: usize) {
print!(" Step {:2}: ", step);
for t in (0..=end).step_by(step) {
if t% 10 == 0 {
print!(" {:7.3}", y);
}
y += step as f64 * f(y);
}
println!();
}
fn main() {
header();
analytic();
for &i in &[2, 5, 10] {
euler(|temp| -0.07 * (temp - 20.0), 100.0, i, 100);
}
} | 886Euler method
| 15rust
| hqyj2 |
object App{
def main(args : Array[String]) = {
def cooling( step : Int ) = {
eulerStep( (step , y) => {-0.07 * (y - 20)} ,
100.0,0,100,step)
}
cooling(10)
cooling(5)
cooling(2)
}
def eulerStep( func : (Int,Double) => Double,y0 : Double,
begin : Int, end : Int , step : Int) = {
println("Step size:%s".format(step))
var current : Int = begin
var y : Double = y0
while( current <= end){
println( "%d%.5f".format(current,y))
current += step
y += step * func(current,y)
}
println("DONE")
}
} | 886Euler method
| 16scala
| p8cbj |
null | 889Evaluate binomial coefficients
| 11kotlin
| dcjnz |
typedef unsigned uint;
int is_prime(uint n)
{
if (!(n%2) || !(n%3)) return 0;
uint p = 1;
while(p*p < n)
if (n%(p += 4) == 0 || n%(p += 2) == 0)
return 0;
return 1;
}
uint reverse(uint n)
{
uint r;
for (r = 0; n; n /= 10)
r = r*10 + (n%10);
return r;
}
int is_emirp(uint n)
{
uint r = reverse(n);
return r != n && is_prime(n) && is_prime(r);
}
int main(int argc, char **argv)
{
uint x, c = 0;
switch(argc) {
case 1: for (x = 11; c < 20; x += 2)
if (is_emirp(x))
printf(, x), ++c;
break;
case 2: for (x = 7701; x < 8000; x += 2)
if (is_emirp(x))
printf(, x);
break;
default:
for (x = 11; ; x += 2)
if (is_emirp(x) && ++c == 10000) {
printf(, x);
break;
}
}
putchar('\n');
return 0;
} | 903Emirp primes
| 5c
| lj4cy |
null | 897Elliptic curve arithmetic
| 11kotlin
| c7h98 |
local fruit = {apple = 0, banana = 1, cherry = 2} | 894Enumerations
| 1lua
| 7w8ru |
from elementary_cellular_automaton import eca, eca_wrap
def rule30bytes(lencells=100):
cells = '1' + '0' * (lencells - 1)
gen = eca(cells, 30)
while True:
yield int(''.join(next(gen)[0] for i in range(8)), 2)
if __name__ == '__main__':
print([b for i,b in zip(range(10), rule30bytes())]) | 898Elementary cellular automaton/Random Number Generator
| 3python
| mgryh |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.