code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
object FindCommonDirectoryPath extends App {
def commonPath(paths: List[String]): String = {
def common(a: List[String], b: List[String]): List[String] = (a, b) match {
case (a :: as, b :: bs) if a equals b => a :: common(as, bs)
case _ => Nil
}
if (paths.length < 2) paths.headOption.getOrElse("")
else paths.map(_.split("/").toList).reduceLeft(common).mkString("/")
}
val test = List(
"/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"
)
println(commonPath(test))
} | 843Find common directory path
| 16scala
| 1i7pf |
null | 857Farey sequence
| 1lua
| zujty |
inFile = io.open("input.txt", "r")
data = inFile:read("*all") | 850File input/output
| 1lua
| i9kot |
from fractions import Fraction
def nextu(a):
n = len(a)
a.append(1)
for i in range(n - 1, 0, -1):
a[i] = i * a[i] + a[i - 1]
return a
def nextv(a):
n = len(a) - 1
b = [(1 - n) * x for x in a]
b.append(1)
for i in range(n):
b[i + 1] += a[i]
return b
def sumpol(n):
u = [0, 1]
v = [[1], [1, 1]]
yield [Fraction(0), Fraction(1)]
for i in range(1, n):
v.append(nextv(v[-1]))
t = [0] * (i + 2)
p = 1
for j, r in enumerate(u):
r = Fraction(r, j + 1)
for k, s in enumerate(v[j + 1]):
t[k] += r * s
yield t
u = nextu(u)
def polstr(a):
s =
q = False
n = len(a) - 1
for i, x in enumerate(reversed(a)):
i = n - i
if i < 2:
m = if i == 1 else
else:
m = % i
c = str(abs(x))
if i > 0:
if c == :
c =
else:
m = + m
if x != 0:
if q:
t = if x > 0 else
s += % (t, c, m)
else:
t = if x > 0 else
s = % (t, c, m)
q = True
if q:
return s
else:
return
for i, p in enumerate(sumpol(10)):
print(i, , polstr(p)) | 852Faulhaber's formula
| 3python
| vbo29 |
import Foundation
func getPrefix(_ text:[String]) -> String? {
var common:String = text[0]
for i in text {
common = i.commonPrefix(with: common)
}
return common
}
var test = ["/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"]
var output:String = getPrefix(test)!
print(output) | 843Find common directory path
| 17swift
| jqu74 |
>>> 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())
...
>>>
>>> def fibword(nmax=37):
... fwords = ['1', '0']
... print('%-3s%10s%-10s%s'% tuple('N Length Entropy Fibword'.split()))
... def pr(n, fwords):
... while len(fwords) < n:
... fwords += [''.join(fwords[-2:][::-1])]
... v = fwords[n-1]
... print('%3i%10i%10.7g%s'% (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))
... for n in range(1, nmax+1): pr(n, fwords)
...
>>> fibword()
N Length Entropy Fibword
1 1 -0 1
2 1 -0 0
3 2 1 01
4 3 0.9182958 010
5 5 0.9709506 01001
6 8 0.954434 01001010
7 13 0.9612366 0100101001001
8 21 0.9587119 <too long>
9 34 0.9596869 <too long>
10 55 0.959316 <too long>
11 89 0.9594579 <too long>
12 144 0.9594038 <too long>
13 233 0.9594244 <too long>
14 377 0.9594165 <too long>
15 610 0.9594196 <too long>
16 987 0.9594184 <too long>
17 1597 0.9594188 <too long>
18 2584 0.9594187 <too long>
19 4181 0.9594187 <too long>
20 6765 0.9594187 <too long>
21 10946 0.9594187 <too long>
22 17711 0.9594187 <too long>
23 28657 0.9594187 <too long>
24 46368 0.9594187 <too long>
25 75025 0.9594187 <too long>
26 121393 0.9594187 <too long>
27 196418 0.9594187 <too long>
28 317811 0.9594187 <too long>
29 514229 0.9594187 <too long>
30 832040 0.9594187 <too long>
31 1346269 0.9594187 <too long>
32 2178309 0.9594187 <too long>
33 3524578 0.9594187 <too long>
34 5702887 0.9594187 <too long>
35 9227465 0.9594187 <too long>
36 14930352 0.9594187 <too long>
37 24157817 0.9594187 <too long>
>>> | 851Fibonacci word
| 3python
| upnvd |
'''Faulhaber's triangle'''
from itertools import accumulate, chain, count, islice
from fractions import Fraction
def faulhaberTriangle(m):
'''List of rows of Faulhaber fractions.'''
def go(rs, n):
def f(x, y):
return Fraction(n, x) * y
xs = list(map(f, islice(count(2), m), rs))
return [Fraction(1 - sum(xs), 1)] + xs
return list(accumulate(
[[]] + list(islice(count(0), 1 + m)),
go
))[1:]
def faulhaberSum(p, n):
'''Sum of the p-th powers of the first n
positive integers.
'''
def go(x, y):
return y * (n ** x)
return sum(
map(go, count(1), faulhaberTriangle(p)[-1])
)
def main():
'''Tests'''
fs = faulhaberTriangle(9)
print(
fTable(__doc__ + ':\n')(str)(
compose(concat)(
fmap(showRatio(3)(3))
)
)(
index(fs)
)(range(0, len(fs)))
)
print('')
print(
faulhaberSum(17, 1000)
)
def fTable(s):
'''Heading -> x display function ->
fx display function -> f -> xs -> tabular string.
'''
def gox(xShow):
def gofx(fxShow):
def gof(f):
def goxs(xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
def arrowed(x, y):
return y.rjust(w, ' ') + ' -> ' + (
fxShow(f(x))
)
return s + '\n' + '\n'.join(
map(arrowed, xs, ys)
)
return goxs
return gof
return gofx
return gox
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
def concat(xs):
'''The concatenation of all the elements
in a list or iterable.
'''
def f(ys):
zs = list(chain(*ys))
return ''.join(zs) if isinstance(ys[0], str) else zs
return (
f(xs) if isinstance(xs, list) else (
chain.from_iterable(xs)
)
) if xs else []
def fmap(f):
'''fmap over a list.
f lifted to a function over a list.
'''
def go(xs):
return list(map(f, xs))
return go
def index(xs):
'''Item at given (zero-based) index.'''
return lambda n: None if 0 > n else (
xs[n] if (
hasattr(xs, )
) else next(islice(xs, n, None))
)
def showRatio(m):
'''Left and right aligned string
representation of the ratio r.
'''
def go(n):
def f(r):
d = r.denominator
return str(r.numerator).rjust(m, ' ') + (
('/' + str(d).ljust(n, ' ')) if 1 != d else (
' ' * (1 + n)
)
)
return f
return go
if __name__ == '__main__':
main() | 855Faulhaber's triangle
| 3python
| i9gof |
entropy <- function(s)
{
if (length(s) > 1)
return(sapply(s, entropy))
freq <- prop.table(table(strsplit(s, '')[1]))
ret <- -sum(freq * log(freq, base=2))
return(ret)
}
fibwords <- function(n)
{
if (n == 1)
fibwords <- "1"
else
fibwords <- c("1", "0")
if (n > 2)
{
for (i in 3:n)
fibwords <- c(fibwords, paste(fibwords[i-1L], fibwords[i-2L], sep=""))
}
str <- if (n > 7) replicate(n-7, "too long") else NULL
fibwords.print <- c(fibwords[1:min(n, 7)], str)
ret <- data.frame(Length=nchar(fibwords), Entropy=entropy(fibwords), Fibwords=fibwords.print)
rownames(ret) <- NULL
return(ret)
} | 851Fibonacci word
| 13r
| cj095 |
package main
import (
"fmt"
"math"
"math/cmplx"
)
func ditfft2(x []float64, y []complex128, n, s int) {
if n == 1 {
y[0] = complex(x[0], 0)
return
}
ditfft2(x, y, n/2, 2*s)
ditfft2(x[s:], y[n/2:], n/2, 2*s)
for k := 0; k < n/2; k++ {
tf := cmplx.Rect(1, -2*math.Pi*float64(k)/float64(n)) * y[k+n/2]
y[k], y[k+n/2] = y[k]+tf, y[k]-tf
}
}
func main() {
x := []float64{1, 1, 1, 1, 0, 0, 0, 0}
y := make([]complex128, len(x))
ditfft2(x, y, len(x), 1)
for _, c := range y {
fmt.Printf("%8.4f\n", c)
}
} | 858Fast Fourier transform
| 0go
| 51qul |
use warnings;
use strict;
use Math::BigRat;
use ntheory qw/euler_phi vecsum/;
sub farey {
my $N = shift;
my @f;
my($m0,$n0, $m1,$n1) = (0, 1, 1, $N);
push @f, Math::BigRat->new("$m0/$n0");
push @f, Math::BigRat->new("$m1/$n1");
while ($f[-1] < 1) {
my $m = int( ($n0 + $N) / $n1) * $m1 - $m0;
my $n = int( ($n0 + $N) / $n1) * $n1 - $n0;
($m0,$n0, $m1,$n1) = ($m1,$n1, $m,$n);
push @f, Math::BigRat->new("$m/$n");
}
@f;
}
sub farey_count { 1 + vecsum(euler_phi(1, shift)); }
for (1 .. 11) {
my @f = map { join "/", $_->parts }
farey($_);
print "F$_: [@f]\n";
}
for (1 .. 10, 100000) {
print "F${_}00: ", farey_count(100*$_), " members\n";
} | 857Farey sequence
| 2perl
| k0fhc |
def binomial(n,k)
if n < 0 or k < 0 or n < k then
return -1
end
if n == 0 or k == 0 then
return 1
end
num = 1
for i in k+1 .. n do
num = num * i
end
denom = 1
for i in 2 .. n-k do
denom = denom * i
end
return num / denom
end
def bernoulli(n)
if n < 0 then
raise
end
a = Array.new(16)
for m in 0 .. n do
a[m] = Rational(1, m + 1)
for j in m.downto(1) do
a[j-1] = (a[j-1] - a[j]) * Rational(j)
end
end
if n!= 1 then
return a[0]
end
return -a[0]
end
def faulhaber(p)
print( % [p])
q = Rational(1, p + 1)
sign = -1
for j in 0 .. p do
sign = -1 * sign
coeff = q * Rational(sign) * Rational(binomial(p+1, j)) * bernoulli(j)
if coeff == 0 then
next
end
if j == 0 then
if coeff!= 1 then
if coeff == -1 then
print
else
print coeff
end
end
else
if coeff == 1 then
print
elsif coeff == -1 then
print
elsif 0 < coeff then
print
print coeff
else
print
print -coeff
end
end
pwr = p + 1 - j
if pwr > 1 then
print % [pwr]
else
print
end
end
print
end
def main
for i in 0 .. 9 do
faulhaber(i)
end
end
main() | 852Faulhaber's formula
| 14ruby
| 51nuj |
import Data.Complex
fft [] = []
fft [x] = [x]
fft xs = zipWith (+) ys ts ++ zipWith (-) ys ts
where n = length xs
ys = fft evens
zs = fft odds
(evens, odds) = split xs
split [] = ([], [])
split [x] = ([x], [])
split (x:y:xs) = (x:xt, y:yt) where (xt, yt) = split xs
ts = zipWith (\z k -> exp' k n * z) zs [0..]
exp' k n = cis $ -2 * pi * (fromIntegral k) / (fromIntegral n)
main = mapM_ print $ fft [1,1,1,1,0,0,0,0] | 858Fast Fourier transform
| 8haskell
| xtmw4 |
package main
import (
"fmt"
"math"
) | 860Factors of a Mersenne number
| 0go
| 4ax52 |
class Frac
attr_accessor:num
attr_accessor:denom
def initialize(n,d)
if d == 0 then
raise ArgumentError.new('d cannot be zero')
end
nn = n
dd = d
if nn == 0 then
dd = 1
elsif dd < 0 then
nn = -nn
dd = -dd
end
g = nn.abs.gcd(dd.abs)
if g > 1 then
nn = nn / g
dd = dd / g
end
@num = nn
@denom = dd
end
def to_s
if self.denom == 1 then
return self.num.to_s
else
return % [self.num, self.denom]
end
end
def -@
return Frac.new(-self.num, self.denom)
end
def +(rhs)
return Frac.new(self.num * rhs.denom + self.denom * rhs.num, rhs.denom * self.denom)
end
def -(rhs)
return Frac.new(self.num * rhs.denom - self.denom * rhs.num, rhs.denom * self.denom)
end
def *(rhs)
return Frac.new(self.num * rhs.num, rhs.denom * self.denom)
end
end
FRAC_ZERO = Frac.new(0, 1)
FRAC_ONE = Frac.new(1, 1)
def bernoulli(n)
if n < 0 then
raise ArgumentError.new('n cannot be negative')
end
a = Array.new(n + 1)
a[0] = FRAC_ZERO
for m in 0 .. n do
a[m] = Frac.new(1, m + 1)
m.downto(1) do |j|
a[j - 1] = (a[j - 1] - a[j]) * Frac.new(j, 1)
end
end
if n!= 1 then
return a[0]
end
return -a[0]
end
def binomial(n, k)
if n < 0 then
raise ArgumentError.new('n cannot be negative')
end
if k < 0 then
raise ArgumentError.new('k cannot be negative')
end
if n < k then
raise ArgumentError.new('n cannot be less than k')
end
if n == 0 or k == 0 then
return 1
end
num = 1
for i in k + 1 .. n do
num = num * i
end
den = 1
for i in 2 .. n - k do
den = den * i
end
return num / den
end
def faulhaberTriangle(p)
coeffs = Array.new(p + 1)
coeffs[0] = FRAC_ZERO
q = Frac.new(1, p + 1)
sign = -1
for j in 0 .. p do
sign = -sign
coeffs[p - j] = q * Frac.new(sign, 1) * Frac.new(binomial(p + 1, j), 1) * bernoulli(j)
end
return coeffs
end
def main
for i in 0 .. 9 do
coeffs = faulhaberTriangle(i)
coeffs.each do |coeff|
print % [coeff]
end
puts
end
end
main() | 855Faulhaber's triangle
| 14ruby
| dl7ns |
import scala.math.Ordering.Implicits.infixOrderingOps
abstract class Frac extends Comparable[Frac] {
val num: BigInt
val denom: BigInt
def unary_-(): Frac = {
Frac(-num, denom)
}
def +(rhs: Frac): Frac = {
Frac(
num * rhs.denom + rhs.num * denom,
denom * rhs.denom
)
}
def -(rhs: Frac): Frac = {
Frac(
num * rhs.denom - rhs.num * denom,
denom * rhs.denom
)
}
def *(rhs: Frac): Frac = {
Frac(num * rhs.num, denom * rhs.denom)
}
override def compareTo(rhs: Frac): Int = {
val ln = num * rhs.denom
val rn = rhs.num * denom
ln.compare(rn)
}
def canEqual(other: Any): Boolean = other.isInstanceOf[Frac]
override def equals(other: Any): Boolean = other match {
case that: Frac =>
(that canEqual this) &&
num == that.num &&
denom == that.denom
case _ => false
}
override def hashCode(): Int = {
val state = Seq(num, denom)
state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
}
override def toString: String = {
if (denom == 1) {
return s"$num"
}
s"$num/$denom"
}
}
object Frac {
val ZERO: Frac = Frac(0)
val ONE: Frac = Frac(1)
def apply(n: BigInt): Frac = new Frac {
val num: BigInt = n
val denom: BigInt = 1
}
def apply(n: BigInt, d: BigInt): Frac = {
if (d == 0) {
throw new IllegalArgumentException("Parameter d may not be zero.")
}
var nn = n
var dd = d
if (nn == 0) {
dd = 1
} else if (dd < 0) {
nn = -nn
dd = -dd
}
val g = nn.gcd(dd)
if (g > 0) {
nn /= g
dd /= g
}
new Frac {
val num: BigInt = nn
val denom: BigInt = dd
}
}
}
object Faulhaber {
def bernoulli(n: Int): Frac = {
if (n < 0) {
throw new IllegalArgumentException("n may not be negative or zero")
}
val a = Array.fill(n + 1)(Frac.ZERO)
for (m <- 0 to n) {
a(m) = Frac(1, m + 1)
for (j <- m to 1 by -1) {
a(j - 1) = (a(j - 1) - a(j)) * Frac(j)
}
} | 852Faulhaber's formula
| 16scala
| 7xzr9 |
def entropy(s)
counts = Hash.new(0.0)
s.each_char { |c| counts[c] += 1 }
leng = s.length
counts.values.reduce(0) do |entropy, count|
freq = count / leng
entropy - freq * Math.log2(freq)
end
end
n_max = 37
words = ['1', '0']
for n in words.length ... n_max
words << words[-1] + words[-2]
end
puts '%3s%9s%15s %s' % %w[N Length Entropy Fibword]
words.each.with_index(1) do |word, i|
puts '%3i%9i%15.12f %s' % [i, word.length, entropy(word), word.length<60? word: '<too long>']
end | 851Fibonacci word
| 14ruby
| 4af5p |
import Data.List
import HFM.Primes (isPrime)
import Control.Monad
import Control.Arrow
int2bin = reverse.unfoldr(\x -> if x==0 then Nothing
else Just ((uncurry.flip$(,))$divMod x 2))
trialfac m = take 1. dropWhile ((/=1).(\q -> foldl (((`mod` q).).pm) 1 bs)) $ qs
where qs = filter (liftM2 (&&) (liftM2 (||) (==1) (==7) .(`mod`8)) isPrime ).
map (succ.(2*m*)). enumFromTo 1 $ m `div` 2
bs = int2bin m
pm n b = 2^b*n*n | 860Factors of a Mersenne number
| 8haskell
| qzyx9 |
import java.math.MathContext
import scala.collection.mutable
abstract class Frac extends Comparable[Frac] {
val num: BigInt
val denom: BigInt
def unary_-(): Frac = {
Frac(-num, denom)
}
def +(rhs: Frac): Frac = {
Frac(
num * rhs.denom + rhs.num * denom,
denom * rhs.denom
)
}
def -(rhs: Frac): Frac = {
Frac(
num * rhs.denom - rhs.num * denom,
denom * rhs.denom
)
}
def *(rhs: Frac): Frac = {
Frac(num * rhs.num, denom * rhs.denom)
}
override def compareTo(rhs: Frac): Int = {
val ln = num * rhs.denom
val rn = rhs.num * denom
ln.compare(rn)
}
def canEqual(other: Any): Boolean = other.isInstanceOf[Frac]
override def equals(other: Any): Boolean = other match {
case that: Frac =>
(that canEqual this) &&
num == that.num &&
denom == that.denom
case _ => false
}
override def hashCode(): Int = {
val state = Seq(num, denom)
state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
}
override def toString: String = {
if (denom == 1) {
return s"$num"
}
s"$num/$denom"
}
}
object Frac {
val ZERO: Frac = Frac(0)
val ONE: Frac = Frac(1)
def apply(n: BigInt): Frac = new Frac {
val num: BigInt = n
val denom: BigInt = 1
}
def apply(n: BigInt, d: BigInt): Frac = {
if (d == 0) {
throw new IllegalArgumentException("Parameter d may not be zero.")
}
var nn = n
var dd = d
if (nn == 0) {
dd = 1
} else if (dd < 0) {
nn = -nn
dd = -dd
}
val g = nn.gcd(dd)
if (g > 0) {
nn /= g
dd /= g
}
new Frac {
val num: BigInt = nn
val denom: BigInt = dd
}
}
}
object Faulhaber {
def bernoulli(n: Int): Frac = {
if (n < 0) {
throw new IllegalArgumentException("n may not be negative or zero")
}
val a = Array.fill(n + 1)(Frac.ZERO)
for (m <- 0 to n) {
a(m) = Frac(1, m + 1)
for (j <- m to 1 by -1) {
a(j - 1) = (a(j - 1) - a(j)) * Frac(j)
}
} | 855Faulhaber's triangle
| 16scala
| 35bzy |
struct Fib<T> {
curr: T,
next: T,
}
impl<T> Fib<T> {
fn new(curr: T, next: T) -> Self {
Fib { curr: curr, next: next, }
}
}
impl Iterator for Fib<String> {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
let ret = self.curr.clone();
self.curr = self.next.clone();
self.next = format!("{}{}", ret, self.next);
Some(ret)
}
}
fn get_entropy(s: &[u8]) -> f64 {
let mut entropy = 0.0;
let mut histogram = [0.0; 256];
for i in 0..s.len() {
histogram.get_mut(s[i] as usize).map(|v| *v += 1.0);
}
for i in 0..256 {
if histogram[i] > 0.0 {
let ratio = histogram[i] / s.len() as f64;
entropy -= ratio * ratio.log2();
}
}
entropy
}
fn main() {
let f = Fib::new("1".to_string(), "0".to_string());
println!("{:10} {:10} {:10} {:60}", "N", "Length", "Entropy", "Word");
for (i, s) in f.take(37).enumerate() {
let word = if s.len() > 60 {"Too long"} else {&*s};
println!("{:10} {:10} {:.10} {:60}", i + 1, s.len(), get_entropy(&s.bytes().collect::<Vec<_>>()), word);
}
} | 851Fibonacci word
| 15rust
| get4o |
null | 851Fibonacci word
| 16scala
| jq67i |
public class FizzBuzz {
public static void main(String[] args) {
for (int number = 1; number <= 100; number++) {
if (number % 15 == 0) {
System.out.println("FizzBuzz");
} else if (number % 3 == 0) {
System.out.println("Fizz");
} else if (number % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(number);
}
}
}
} | 835FizzBuzz
| 9java
| 9j2mu |
import static java.lang.Math.*;
public class FastFourierTransform {
public static int bitReverse(int n, int bits) {
int reversedN = n;
int count = bits - 1;
n >>= 1;
while (n > 0) {
reversedN = (reversedN << 1) | (n & 1);
count--;
n >>= 1;
}
return ((reversedN << count) & ((1 << bits) - 1));
}
static void fft(Complex[] buffer) {
int bits = (int) (log(buffer.length) / log(2));
for (int j = 1; j < buffer.length / 2; j++) {
int swapPos = bitReverse(j, bits);
Complex temp = buffer[j];
buffer[j] = buffer[swapPos];
buffer[swapPos] = temp;
}
for (int N = 2; N <= buffer.length; N <<= 1) {
for (int i = 0; i < buffer.length; i += N) {
for (int k = 0; k < N / 2; k++) {
int evenIndex = i + k;
int oddIndex = i + k + (N / 2);
Complex even = buffer[evenIndex];
Complex odd = buffer[oddIndex];
double term = (-2 * PI * k) / (double) N;
Complex exp = (new Complex(cos(term), sin(term)).mult(odd));
buffer[evenIndex] = even.add(exp);
buffer[oddIndex] = even.sub(exp);
}
}
}
}
public static void main(String[] args) {
double[] input = {1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0};
Complex[] cinput = new Complex[input.length];
for (int i = 0; i < input.length; i++)
cinput[i] = new Complex(input[i], 0.0);
fft(cinput);
System.out.println("Results:");
for (Complex c : cinput) {
System.out.println(c);
}
}
}
class Complex {
public final double re;
public final double im;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
re = r;
im = i;
}
public Complex add(Complex b) {
return new Complex(this.re + b.re, this.im + b.im);
}
public Complex sub(Complex b) {
return new Complex(this.re - b.re, this.im - b.im);
}
public Complex mult(Complex b) {
return new Complex(this.re * b.re - this.im * b.im,
this.re * b.im + this.im * b.re);
}
@Override
public String toString() {
return String.format("(%f,%f)", re, im);
}
} | 858Fast Fourier transform
| 9java
| b8fk3 |
import java.math.BigInteger;
class MersenneFactorCheck
{
private final static BigInteger TWO = BigInteger.valueOf(2);
public static boolean isPrime(long n)
{
if (n == 2)
return true;
if ((n < 2) || ((n & 1) == 0))
return false;
long maxFactor = (long)Math.sqrt((double)n);
for (long possibleFactor = 3; possibleFactor <= maxFactor; possibleFactor += 2)
if ((n % possibleFactor) == 0)
return false;
return true;
}
public static BigInteger findFactorMersenneNumber(int primeP)
{
if (primeP <= 0)
throw new IllegalArgumentException();
BigInteger bigP = BigInteger.valueOf(primeP);
BigInteger m = BigInteger.ONE.shiftLeft(primeP).subtract(BigInteger.ONE); | 860Factors of a Mersenne number
| 9java
| podb3 |
from fractions import Fraction
class Fr(Fraction):
def __repr__(self):
return '(%s/%s)'% (self.numerator, self.denominator)
def farey(n, length=False):
if not length:
return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})
else:
return (n*(n+3))
if __name__ == '__main__':
print('Farey sequence for order 1 through 11 (inclusive):')
for n in range(1, 12):
print(farey(n))
print('Number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds:')
print([farey(i, length=True) for i in range(100, 1001, 100)]) | 857Farey sequence
| 3python
| b8tkr |
package main
import "fmt"
func g(i []int, c chan<- int) {
var sum int
b := append([]int(nil), i...) | 859Fibonacci n-step number sequences
| 0go
| vbe2m |
package main
import (
"fmt"
"math/rand"
)
func main() {
a := rand.Perm(20)
fmt.Println(a) | 853Filter
| 0go
| omr8q |
var fizzBuzz = function () {
var i, output;
for (i = 1; i < 101; i += 1) {
output = '';
if (!(i % 3)) { output += 'Fizz'; }
if (!(i % 5)) { output += 'Buzz'; }
console.log(output || i); | 835FizzBuzz
| 10javascript
| u1gvb |
function icfft(amplitudes)
{
var N = amplitudes.length;
var iN = 1 / N; | 858Fast Fourier transform
| 10javascript
| wfye2 |
function mersenne_factor(p){
var limit, k, q
limit = Math.sqrt(Math.pow(2,p) - 1)
k = 1
while ((2*k*p - 1) < limit){
q = 2*k*p + 1
if (isPrime(q) && (q % 8 == 1 || q % 8 == 7) && trial_factor(2,p,q)){
return q | 860Factors of a Mersenne number
| 10javascript
| xt6w9 |
farey <- function(n, length_only = FALSE) {
a <- 0
b <- 1
c <- 1
d <- n
if (!length_only)
cat(a, "/", b, sep = "")
count <- 1
while (c <= n) {
count <- count + 1
k <- ((n + b) %/% d)
next_c <- k * c - a
next_d <- k * d - b
a <- c
b <- d
c <- next_c
d <- next_d
if (!length_only)
cat(" ", a, "/", b, sep = "")
}
if (length_only)
cat(count, "items")
cat("\n")
}
for (i in 1:11) {
cat(i, ": ", sep = "")
farey(i)
}
for (i in 100 * 1:10) {
cat(i, ": ", sep = "")
farey(i, length_only = TRUE)
} | 857Farey sequence
| 13r
| 7xiry |
def fib = { List seed, int k=10 ->
assert seed: "The seed list must be non-null and non-empty"
assert seed.every { it instanceof Number }: "Every member of the seed must be a number"
def n = seed.size()
assert n > 1: "The seed must contain at least two elements"
List result = [] + seed
if (k < n) {
result[0..k]
} else {
(n..k).inject(result) { res, kk ->
res << res[-n..-1].sum()
}
}
} | 859Fibonacci n-step number sequences
| 7groovy
| mrky5 |
def evens = [1, 2, 3, 4, 5].findAll{it % 2 == 0} | 853Filter
| 7groovy
| xtvwl |
import Foundation
struct Fib: Sequence, IteratorProtocol {
private var cur: String
private var nex: String
init(cur: String, nex: String) {
self.cur = cur
self.nex = nex
}
mutating func next() -> String? {
let ret = cur
cur = nex
nex = "\(ret)\(nex)"
return ret
}
}
func getEntropy(_ s: [Int]) -> Double {
var entropy = 0.0
var hist = Array(repeating: 0.0, count: 256)
for i in 0..<s.count {
hist[s[i]] += 1
}
for i in 0..<256 where hist[i] > 0 {
let rat = hist[i] / Double(s.count)
entropy -= rat * log2(rat)
}
return entropy
}
for (i, str) in Fib(cur: "1", nex: "0").prefix(37).enumerated() {
let ent = getEntropy(str.map({ Int($0.asciiValue!) }))
print("i: \(i) len: \(str.count) entropy: \(ent)")
} | 851Fibonacci word
| 17swift
| 51du8 |
null | 860Factors of a Mersenne number
| 11kotlin
| 7x0r4 |
import Data.List (tails)
import Control.Monad (zipWithM_)
fiblike :: [Integer] -> [Integer]
fiblike st = xs where
xs = st ++ map (sum . take n) (tails xs)
n = length st
nstep :: Int -> [Integer]
nstep n = fiblike $ take n $ 1: iterate (2*) 1
main :: IO ()
main = do
print $ take 10 $ fiblike [1,1]
print $ take 10 $ fiblike [2,1]
zipWithM_ (\n name -> do putStr (name ++ "nacci -> ")
print $ take 15 $ nstep n)
[2..] (words "fibo tribo tetra penta hexa hepta octo nona deca") | 859Fibonacci n-step number sequences
| 8haskell
| ed3ai |
ary = [1..10]
evens = [x | x <- ary, even x] | 853Filter
| 8haskell
| 2k0ll |
open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!";
open my $fh_out, '>', 'output.txt' or die "could not open <output.txt> for writing: $!";
binmode $fh_out;
print $fh_out $_ while <$fh_in>;
close $fh_in;
close $fh_out; | 850File input/output
| 2perl
| gez4e |
def farey(n, length=false)
if length
(n*(n+3))/2 - (2..n).sum{|k| farey(n/k, true)}
else
(1..n).each_with_object([]){|k,a|(0..k).each{|m|a << Rational(m,k)}}.uniq.sort
end
end
puts 'Farey sequence for order 1 through 11 (inclusive):'
for n in 1..11
puts + farey(n).join()
end
puts 'Number of fractions in the Farey sequence:'
for i in (100..1000).step(100)
puts % [i, farey(i, true)]
end | 857Farey sequence
| 14ruby
| 1i3pw |
<?php
if (!$in = fopen('input.txt', 'r')) {
die('Could not open input file.');
}
if (!$out = fopen('output.txt', 'w')) {
die('Could not open output file.');
}
while (!feof($in)) {
$data = fread($in, 512);
fwrite($out, $data);
}
fclose($out);
fclose($in);
?> | 850File input/output
| 12php
| ncbig |
import java.lang.Math.*
class Complex(val re: Double, val im: Double) {
operator infix fun plus(x: Complex) = Complex(re + x.re, im + x.im)
operator infix fun minus(x: Complex) = Complex(re - x.re, im - x.im)
operator infix fun times(x: Double) = Complex(re * x, im * x)
operator infix fun times(x: Complex) = Complex(re * x.re - im * x.im, re * x.im + im * x.re)
operator infix fun div(x: Double) = Complex(re / x, im / x)
val exp: Complex by lazy { Complex(cos(im), sin(im)) * (cosh(re) + sinh(re)) }
override fun toString() = when {
b == "0.000" -> a
a == "0.000" -> b + 'i'
im > 0 -> a + " + " + b + 'i'
else -> a + " - " + b + 'i'
}
private val a = "%1.3f".format(re)
private val b = "%1.3f".format(abs(im))
} | 858Fast Fourier transform
| 11kotlin
| rw8go |
#[derive(Copy, Clone)]
struct Fraction {
numerator: u32,
denominator: u32,
}
use std::fmt;
impl fmt::Display for Fraction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}/{}", self.numerator, self.denominator)
}
}
impl Fraction {
fn new(n: u32, d: u32) -> Fraction {
Fraction {
numerator: n,
denominator: d,
}
}
}
fn farey_sequence(n: u32) -> impl std::iter::Iterator<Item = Fraction> {
let mut a = 0;
let mut b = 1;
let mut c = 1;
let mut d = n;
std::iter::from_fn(move || {
if a > n {
return None;
}
let result = Fraction::new(a, b);
let k = (n + b) / d;
let next_c = k * c - a;
let next_d = k * d - b;
a = c;
b = d;
c = next_c;
d = next_d;
Some(result)
})
}
fn main() {
for n in 1..=11 {
print!("{}:", n);
for f in farey_sequence(n) {
print!(" {}", f);
}
println!();
}
for n in (100..=1000).step_by(100) {
println!("{}: {}", n, farey_sequence(n).count());
}
} | 857Farey sequence
| 15rust
| an614 |
object FareySequence {
def fareySequence(n: Int, start: (Int, Int), stop: (Int, Int)): LazyList[(Int, Int)] = {
val (nominator_l, denominator_l) = start
val (nominator_r, denominator_r) = stop
val mediant = ((nominator_l + nominator_r), (denominator_l + denominator_r))
if (mediant._2 <= n) fareySequence(n, start, mediant) ++ mediant #:: fareySequence(n, mediant, stop)
else LazyList.empty
}
def farey(n: Int, start: (Int, Int) = (0, 1), stop: (Int, Int) = (1, 1)): LazyList[(Int, Int)] = {
start #:: fareySequence(n, start, stop) ++ stop #:: LazyList.empty[(Int, Int)]
}
def main(args: Array[String]): Unit = {
for (i <- 1 to 11) {
println(s"$i: " + farey(i).map(e => s"${e._1}/${e._2}").mkString(", "))
}
println
for (i <- 100 to 1000 by 100) {
println(s"$i: " + farey(i).length + " elements")
}
}
} | 857Farey sequence
| 16scala
| xt9wg |
class Fibonacci
{
public static int[] lucas(int n, int numRequested)
{
if (n < 2)
throw new IllegalArgumentException("Fibonacci value must be at least 2");
return fibonacci((n == 2) ? new int[] { 2, 1 } : lucas(n - 1, n), numRequested);
}
public static int[] fibonacci(int n, int numRequested)
{
if (n < 2)
throw new IllegalArgumentException("Fibonacci value must be at least 2");
return fibonacci((n == 2) ? new int[] { 1, 1 } : fibonacci(n - 1, n), numRequested);
}
public static int[] fibonacci(int[] startingValues, int numRequested)
{
int[] output = new int[numRequested];
int n = startingValues.length;
System.arraycopy(startingValues, 0, output, 0, n);
for (int i = n; i < numRequested; i++)
for (int j = 1; j <= n; j++)
output[i] += output[i - j];
return output;
}
public static void main(String[] args)
{
for (int n = 2; n <= 10; n++)
{
System.out.print("nacci(" + n + "):");
for (int value : fibonacci(n, 15))
System.out.print(" " + value);
System.out.println();
}
for (int n = 2; n <= 10; n++)
{
System.out.print("lucas(" + n + "):");
for (int value : lucas(n, 15))
System.out.print(" " + value);
System.out.println();
}
}
} | 859Fibonacci n-step number sequences
| 9java
| hsijm |
function fib(arity, len) {
return nacci(nacci([1,1], arity, arity), arity, len);
}
function lucas(arity, len) {
return nacci(nacci([2,1], arity, arity), arity, len);
}
function nacci(a, arity, len) {
while (a.length < len) {
var sum = 0;
for (var i = Math.max(0, a.length - arity); i < a.length; i++)
sum += a[i];
a.push(sum);
}
return a;
}
function main() {
for (var arity = 2; arity <= 10; arity++)
console.log("fib(" + arity + "): " + fib(arity, 15));
for (var arity = 2; arity <= 10; arity++)
console.log("lucas(" + arity + "): " + lucas(arity, 15));
}
main(); | 859Fibonacci n-step number sequences
| 10javascript
| anz10 |
int[] array = {1, 2, 3, 4, 5 };
List<Integer> evensList = new ArrayList<Integer>();
for (int i: array) {
if (i % 2 == 0) evensList.add(i);
}
int[] evens = evensList.toArray(new int[0]); | 853Filter
| 9java
| 64a3z |
use strict;
use utf8;
sub factors {
my $n = shift;
my $p = 2;
my @out;
while ($n >= $p * $p) {
while ($n % $p == 0) {
push @out, $p;
$n /= $p;
}
$p = next_prime($p);
}
push @out, $n if $n > 1 || !@out;
@out;
}
sub next_prime {
my $p = shift;
do { $p = $p == 2 ? 3 : $p + 2 } until is_prime($p);
$p;
}
my %pcache;
sub is_prime {
my $x = shift;
$pcache{$x} //= (factors($x) == 1)
}
sub mtest {
my @bits = split "", sprintf("%b", shift);
my $p = shift;
my $sq = 1;
while (@bits) {
$sq = $sq * $sq;
$sq *= 2 if shift @bits;
$sq %= $p;
}
$sq == 1;
}
for my $m (2 .. 60, 929) {
next unless is_prime($m);
use bigint;
my ($f, $k, $x) = (0, 0, 2**$m - 1);
my $q;
while (++$k) {
$q = 2 * $k * $m + 1;
next if (($q & 7) != 1 && ($q & 7) != 7);
next unless is_prime($q);
last if $q * $q > $x;
last if $f = mtest($m, $q);
}
print $f? "M$m = $x = $q @{[$x / $q]}\n"
: "M$m = $x is prime\n";
} | 860Factors of a Mersenne number
| 2perl
| f25d7 |
typedef struct {
int *list;
short count;
} Factors;
void xferFactors( Factors *fctrs, int *flist, int flix )
{
int ix, ij;
int newSize = fctrs->count + flix;
if (newSize > flix) {
fctrs->list = realloc( fctrs->list, newSize * sizeof(int));
}
else {
fctrs->list = malloc( newSize * sizeof(int));
}
for (ij=0,ix=fctrs->count; ix<newSize; ij++,ix++) {
fctrs->list[ix] = flist[ij];
}
fctrs->count = newSize;
}
Factors *factor( int num, Factors *fctrs)
{
int flist[301], flix;
int dvsr;
flix = 0;
fctrs->count = 0;
free(fctrs->list);
fctrs->list = NULL;
for (dvsr=1; dvsr*dvsr < num; dvsr++) {
if (num % dvsr != 0) continue;
if ( flix == 300) {
xferFactors( fctrs, flist, flix );
flix = 0;
}
flist[flix++] = dvsr;
flist[flix++] = num/dvsr;
}
if (dvsr*dvsr == num)
flist[flix++] = dvsr;
if (flix > 0)
xferFactors( fctrs, flist, flix );
return fctrs;
}
int main(int argc, char*argv[])
{
int nums2factor[] = { 2059, 223092870, 3135, 45 };
Factors ftors = { NULL, 0};
char sep;
int i,j;
for (i=0; i<4; i++) {
factor( nums2factor[i], &ftors );
printf(, nums2factor[i]);
sep = ' ';
for (j=0; j<ftors.count; j++) {
printf(, sep, ftors.list[j]);
sep = ',';
}
printf();
}
return 0;
} | 861Factors of an integer
| 5c
| 1idpj |
null | 858Fast Fourier transform
| 1lua
| 7xoru |
class Farey {
let n: Int
init(_ x: Int) {
n = x
} | 857Farey sequence
| 17swift
| pozbl |
var arr = [1,2,3,4,5];
var evens = arr.filter(function(a) {return a % 2 == 0}); | 853Filter
| 10javascript
| lhscf |
import shutil
shutil.copyfile('input.txt', 'output.txt') | 850File input/output
| 3python
| rw3gq |
echo 'M929 has a factor: ', mersenneFactor(929), '</br>';
function mersenneFactor($p) {
$limit = sqrt(pow(2, $p) - 1);
for ($k = 1; 2 * $p * $k - 1 < $limit; $k++) {
$q = 2 * $p * $k + 1;
if (isPrime($q) && ($q % 8 == 1 || $q % 8 == 7) && bcpowmod(, , ) == ) {
return $q;
}
}
return 0;
}
function isPrime($n) {
if ($n < 2 || $n % 2 == 0) return $n == 2;
for ($i = 3; $i * $i <= $n; $i += 2) {
if ($n % $i == 0) {
return false;
}
}
return true;
} | 860Factors of a Mersenne number
| 12php
| hsojf |
null | 859Fibonacci n-step number sequences
| 11kotlin
| 4aq57 |
fun fizzBuzz() {
for (number in 1..100) {
println(
when {
number % 15 == 0 -> "FizzBuzz"
number % 3 == 0 -> "Fizz"
number % 5 == 0 -> "Buzz"
else -> number
}
)
}
} | 835FizzBuzz
| 11kotlin
| z5yts |
src <- file("input.txt", "r")
dest <- file("output.txt", "w")
fc <- readLines(src, -1)
writeLines(fc, dest)
close(src); close(dest) | 850File input/output
| 13r
| updvx |
function nStepFibs (seq, limit)
local iMax, sum = #seq - 1
while #seq < limit do
sum = 0
for i = 0, iMax do sum = sum + seq[#seq - i] end
table.insert(seq, sum)
end
return seq
end
local fibSeqs = {
{name = "Fibonacci", values = {1, 1} },
{name = "Tribonacci", values = {1, 1, 2} },
{name = "Tetranacci", values = {1, 1, 2, 4}},
{name = "Lucas", values = {2, 1} }
}
for _, sequence in pairs(fibSeqs) do
io.write(sequence.name .. ": ")
print(table.concat(nStepFibs(sequence.values, 10), " "))
end | 859Fibonacci n-step number sequences
| 1lua
| ges4j |
def is_prime(number):
return True
def m_factor(p):
max_k = 16384 / p
for k in xrange(max_k):
q = 2*p*k + 1
if not is_prime(q):
continue
elif q% 8 != 1 and q% 8 != 7:
continue
elif pow(2, p, q) == 1:
return q
return None
if __name__ == '__main__':
exponent = int(raw_input())
if not is_prime(exponent):
print % exponent
else:
factor = m_factor(exponent)
if not factor:
print % exponent
else:
print % (exponent, factor) | 860Factors of a Mersenne number
| 3python
| tv4fw |
null | 853Filter
| 11kotlin
| dlhnz |
(defn factors [n]
(filter #(zero? (rem n %)) (range 1 (inc n))))
(print (factors 45)) | 861Factors of an integer
| 6clojure
| qz6xt |
require 'prime'
def mersenne_factor(p)
limit = Math.sqrt(2**p - 1)
k = 1
while (2*k*p - 1) < limit
q = 2*k*p + 1
if q.prime? and (q % 8 == 1 or q % 8 == 7) and trial_factor(2,p,q)
return q
end
k += 1
end
nil
end
def trial_factor(base, exp, mod)
square = 1
( % exp).each_char {|bit| square = square**2 * (bit == ? base: 1) % mod}
(square == 1)
end
def check_mersenne(p)
print
f = mersenne_factor(p)
if f.nil?
puts
else
puts
end
end
Prime.each(53) { |p| check_mersenne p }
check_mersenne 929 | 860Factors of a Mersenne number
| 14ruby
| 35rz7 |
str = File.open('input.txt', 'rb') {|f| f.read}
File.open('output.txt', 'wb') {|f| f.write str} | 850File input/output
| 14ruby
| jqy7x |
fn bit_count(mut n: usize) -> usize {
let mut count = 0;
while n > 0 {
n >>= 1;
count += 1;
}
count
}
fn mod_pow(p: usize, n: usize) -> usize {
let mut square = 1;
let mut bits = bit_count(p);
while bits > 0 {
square = square * square;
bits -= 1;
if (p & (1 << bits))!= 0 {
square <<= 1;
}
square%= n;
}
return square;
}
fn is_prime(n: usize) -> bool {
if n < 2 {
return false;
}
if n% 2 == 0 {
return n == 2;
}
if n% 3 == 0 {
return n == 3;
}
let mut p = 5;
while p * p <= n {
if n% p == 0 {
return false;
}
p += 2;
if n% p == 0 {
return false;
}
p += 4;
}
true
}
fn find_mersenne_factor(p: usize) -> usize {
let mut k = 0;
loop {
k += 1;
let q = 2 * k * p + 1;
if q% 8 == 1 || q% 8 == 7 {
if mod_pow(p, q) == 1 && is_prime(p) {
return q;
}
}
}
}
fn main() {
println!("{}", find_mersenne_factor(929));
} | 860Factors of a Mersenne number
| 15rust
| 6473l |
object FactorsOfAMersenneNumber extends App {
val two: BigInt = 2 | 860Factors of a Mersenne number
| 16scala
| 97km5 |
use std::fs::File;
use std::io::{Read, Write};
fn main() {
let mut file = File::open("input.txt").unwrap();
let mut data = Vec::new();
file.read_to_end(&mut data).unwrap();
let mut file = File::create("output.txt").unwrap();
file.write_all(&data).unwrap();
} | 850File input/output
| 15rust
| hsmj2 |
import java.io.{ FileNotFoundException, PrintWriter }
object FileIO extends App {
try {
val MyFileTxtTarget = new PrintWriter("output.txt")
scala.io.Source.fromFile("input.txt").getLines().foreach(MyFileTxtTarget.println)
MyFileTxtTarget.close()
} catch {
case e: FileNotFoundException => println(e.getLocalizedMessage())
case e: Throwable => {
println("Some other exception type:")
e.printStackTrace()
}
}
} | 850File input/output
| 16scala
| polbj |
$ fib=1;j=1;while((fib<100));do echo $fib;((k=fib+j,fib=j,j=k));done | 862Fibonacci sequence
| 4bash
| dl2np |
use strict;
use warnings;
use feature <say signatures>;
no warnings 'experimental';
use List::Util <max sum>;
sub fib_n ($n = 2, $xs = [1], $max = 100) {
my @xs = @$xs;
while ( $max > (my $len = @xs) ) {
push @xs, sum @xs[ max($len - $n, 0) .. $len-1 ];
}
@xs
}
say $_-1 . ': ' . join ' ', (fib_n $_)[0..19] for 2..10;
say "\nLucas: " . join ' ', fib_n(2, [2,1], 20); | 859Fibonacci n-step number sequences
| 2perl
| i9vo3 |
use strict;
use warnings;
use Math::Complex;
sub fft {
return @_ if @_ == 1;
my @evn = fft(@_[grep { not $_ % 2 } 0 .. $
my @odd = fft(@_[grep { $_ % 2 } 1 .. $
my $twd = 2*i* pi / @_;
$odd[$_] *= exp( $_ * -$twd ) for 0 .. $
return
(map { $evn[$_] + $odd[$_] } 0 .. $
(map { $evn[$_] - $odd[$_] } 0 .. $
}
print "$_\n" for fft qw(1 1 1 1 0 0 0 0); | 858Fast Fourier transform
| 2perl
| dl4nw |
import Foundation
extension BinaryInteger {
var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) where self% i == 0 {
return false
}
return true
}
func modPow(exp: Self, mod: Self) -> Self {
guard exp!= 0 else {
return 1
}
var res = Self(1)
var base = self% mod
var exp = exp
while true {
if exp & 1 == 1 {
res *= base
res%= mod
}
if exp == 1 {
return res
}
exp >>= 1
base *= base
base%= mod
}
}
}
func mFactor(exp: Int) -> Int? {
for k in 0..<16384 {
let q = 2*exp*k + 1
if!q.isPrime {
continue
} else if q% 8!= 1 && q% 8!= 7 {
continue
} else if 2.modPow(exp: exp, mod: q) == 1 {
return q
}
}
return nil
}
print(mFactor(exp: 929)!) | 860Factors of a Mersenne number
| 17swift
| zugtu |
<?php
function fib_n_step($x, &$series = array(1, 1), $n = 15)
{
$count = count($series);
if($count > $x && $count == $n)
{
return $series;
}
if($count < $n)
{
if($count >= $x)
{
fib($series, $x, $count);
return fib_n_step($x, $series, $n);
}
else
{
while(count($series) < $x )
{
$count = count($series);
fib($series, $count, $count);
}
return fib_n_step($x, $series, $n);
}
}
return $series;
}
function fib(&$series, $n, $i)
{
$end = 0;
for($j = $n; $j > 0; $j--)
{
$end += $series[$i-$j];
}
$series[$i] = $end;
}
header('Content-Type: text/plain');
$steps = array(
'LUCAS' => array(2, array(2, 1)),
'FIBONACCI' => array(2, array(1, 1)),
'TRIBONACCI' => array(3, array(1, 1, 2)),
'TETRANACCI' => array(4, array(1, 1, 2, 4)),
'PENTANACCI' => array(5, array(1, 1, 2, 4)),
'HEXANACCI' => array(6, array(1, 1, 2, 4)),
'HEPTANACCI' => array(7, array(1, 1, 2, 4)),
'OCTONACCI' => array(8, array(1, 1, 2, 4)),
'NONANACCI' => array(9, array(1, 1, 2, 4)),
'DECANACCI' => array(10, array(1, 1, 2, 4)),
);
foreach($steps as $name=>$pair)
{
$ser = fib_n_step($pair[0],$pair[1]);
$n = count($ser)-1;
echo $name..implode(',', $ser) . ;
} | 859Fibonacci n-step number sequences
| 12php
| rw0ge |
import 'dart:math';
factors(n)
{
var factorsArr = [];
factorsArr.add(n);
factorsArr.add(1);
for(var test = n - 1; test >= sqrt(n).toInt(); test--)
if(n% test == 0)
{
factorsArr.add(test);
factorsArr.add(n / test);
}
return factorsArr;
}
void main() {
print(factors(5688));
} | 861Factors of an integer
| 18dart
| 7xsr7 |
<?php
class Complex
{
public $real;
public $imaginary;
function __construct($real, $imaginary){
$this->real = $real;
$this->imaginary = $imaginary;
}
function Add($other, $dst){
$dst->real = $this->real + $other->real;
$dst->imaginary = $this->imaginary + $other->imaginary;
return $dst;
}
function Subtract($other, $dst){
$dst->real = $this->real - $other->real;
$dst->imaginary = $this->imaginary - $other->imaginary;
return $dst;
}
function Multiply($other, $dst){
$r = $this->real * $other->real - $this->imaginary * $other->imaginary;
$dst->imaginary = $this->real * $other->imaginary + $this->imaginary * $other->real;
$dst->real = $r;
return $dst;
}
function ComplexExponential($dst){
$er = exp($this->real);
$dst->real = $er * cos($this->imaginary);
$dst->imaginary = $er * sin($this->imaginary);
return $dst;
}
} | 858Fast Fourier transform
| 12php
| jqi7z |
function filter(t, func)
local ret = {}
for i, v in ipairs(t) do
ret[#ret+1] = func(v) and v or nil
end
return ret
end
function even(a) return a % 2 == 0 end
print(unpack(filter({1, 2, 3, 4 ,5, 6, 7, 8, 9, 10}, even))) | 853Filter
| 1lua
| f2kdp |
from cmath import exp, pi
def fft(x):
N = len(x)
if N <= 1: return x
even = fft(x[0::2])
odd = fft(x[1::2])
T= [exp(-2j*pi*k/N)*odd[k] for k in range(N
return [even[k] + T[k] for k in range(N
[even[k] - T[k] for k in range(N
print( ' '.join(% abs(f)
for f in fft([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0])) ) | 858Fast Fourier transform
| 3python
| f2gde |
>>> def fiblike(start):
addnum = len(start)
memo = start[:]
def fibber(n):
try:
return memo[n]
except IndexError:
ans = sum(fibber(i) for i in range(n-addnum, n))
memo.append(ans)
return ans
return fibber
>>> fibo = fiblike([1,1])
>>> [fibo(i) for i in range(10)]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> lucas = fiblike([2,1])
>>> [lucas(i) for i in range(10)]
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76]
>>> for n, name in zip(range(2,11), 'fibo tribo tetra penta hexa hepta octo nona deca'.split()):
fibber = fiblike([1] + [2**i for i in range(n-1)])
print('n=%2i,%5snacci ->%s ...'% (n, name, ' '.join(str(fibber(i)) for i in range(15))))
n= 2, fibonacci -> 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
n= 3, tribonacci -> 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
n= 4, tetranacci -> 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
n= 5, pentanacci -> 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
n= 6, hexanacci -> 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
n= 7, heptanacci -> 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
n= 8, octonacci -> 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
n= 9, nonanacci -> 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
n=10, decanacci -> 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
>>> | 859Fibonacci n-step number sequences
| 3python
| ncuiz |
fft(c(1,1,1,1,0,0,0,0)) | 858Fast Fourier transform
| 13r
| omv84 |
for i = 1, 100 do
if i % 15 == 0 then
print("FizzBuzz")
elseif i % 3 == 0 then
print("Fizz")
elseif i % 5 == 0 then
print("Buzz")
else
print(i)
end
end | 835FizzBuzz
| 1lua
| 34mzo |
def fft(vec)
return vec if vec.size <= 1
evens_odds = vec.partition.with_index{|_,i| i.even?}
evens, odds = evens_odds.map{|even_odd| fft(even_odd)*2}
evens.zip(odds).map.with_index do |(even, odd),i|
even + odd * Math::E ** Complex(0, -2 * Math::PI * i / vec.size)
end
end
fft([1,1,1,1,0,0,0,0]).each{|c| puts % c.rect} | 858Fast Fourier transform
| 14ruby
| zu7tw |
extern crate num;
use num::complex::Complex;
use std::f64::consts::PI;
const I: Complex<f64> = Complex { re: 0.0, im: 1.0 };
pub fn fft(input: &[Complex<f64>]) -> Vec<Complex<f64>> {
fn fft_inner(
buf_a: &mut [Complex<f64>],
buf_b: &mut [Complex<f64>],
n: usize, | 858Fast Fourier transform
| 15rust
| 35jz8 |
import scala.math.{ Pi, cos, sin, cosh, sinh, abs }
case class Complex(re: Double, im: Double) {
def +(x: Complex): Complex = Complex(re + x.re, im + x.im)
def -(x: Complex): Complex = Complex(re - x.re, im - x.im)
def *(x: Double): Complex = Complex(re * x, im * x)
def *(x: Complex): Complex = Complex(re * x.re - im * x.im, re * x.im + im * x.re)
def /(x: Double): Complex = Complex(re / x, im / x)
override def toString(): String = {
val a = "%1.3f" format re
val b = "%1.3f" format abs(im)
(a,b) match {
case (_, "0.000") => a
case ("0.000", _) => b + "i"
case (_, _) if im > 0 => a + " + " + b + "i"
case (_, _) => a + " - " + b + "i"
}
}
}
def exp(c: Complex) : Complex = {
val r = (cosh(c.re) + sinh(c.re))
Complex(cos(c.im), sin(c.im)) * r
} | 858Fast Fourier transform
| 16scala
| mrbyc |
def anynacci(start_sequence, count)
n = start_sequence.length
result = start_sequence.dup
(count-n).times do
result << result.last(n).sum
end
result
end
naccis = { lucas: [2,1],
fibonacci: [1,1],
tribonacci: [1,1,2],
tetranacci: [1,1,2,4],
pentanacci: [1,1,2,4,8],
hexanacci: [1,1,2,4,8,16],
heptanacci: [1,1,2,4,8,16,32],
octonacci: [1,1,2,4,8,16,32,64],
nonanacci: [1,1,2,4,8,16,32,64,128],
decanacci: [1,1,2,4,8,16,32,64,128,256] }
naccis.each {|name, seq| puts % [name, anynacci(seq, 15)]} | 859Fibonacci n-step number sequences
| 14ruby
| f24dr |
struct GenFibonacci {
buf: Vec<u64>,
sum: u64,
idx: usize,
}
impl Iterator for GenFibonacci {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let result = Some(self.sum);
self.sum -= self.buf[self.idx];
self.buf[self.idx] += self.sum;
self.sum += self.buf[self.idx];
self.idx = (self.idx + 1)% self.buf.len();
result
}
}
fn print(buf: Vec<u64>, len: usize) {
let mut sum = 0;
for &elt in buf.iter() { sum += elt; print!("\t{}", elt); }
let iter = GenFibonacci { buf: buf, sum: sum, idx: 0 };
for x in iter.take(len) {
print!("\t{}", x);
}
}
fn main() {
print!("Fib2:");
print(vec![1,1], 10 - 2);
print!("\nFib3:");
print(vec![1,1,2], 10 - 3);
print!("\nFib4:");
print(vec![1,1,2,4], 10 - 4);
print!("\nLucas:");
print(vec![2,1], 10 - 2);
} | 859Fibonacci n-step number sequences
| 15rust
| tvgfd |
long long fibb(long long a, long long b, int n) {
return (--n>0)?(fibb(b, a+b, n)):(a);
} | 862Fibonacci sequence
| 5c
| tvuf4 |
null | 859Fibonacci n-step number sequences
| 16scala
| 64j31 |
import Foundation
import Numerics
typealias Complex = Numerics.Complex<Double>
extension Complex {
var exp: Complex {
Complex(cos(imaginary), sin(imaginary)) * Complex(cosh(real), sinh(real))
}
var pretty: String {
let fmt = { String(format: "%1.3f", $0) }
let re = fmt(real)
let im = fmt(abs(imaginary))
if im == "0.000" {
return re
} else if re == "0.000" {
return im
} else if imaginary > 0 {
return re + " + " + im + "i"
} else {
return re + " - " + im + "i"
}
}
}
func fft(_ array: [Complex]) -> [Complex] { _fft(array, direction: Complex(0.0, 2.0), scalar: 1) }
func rfft(_ array: [Complex]) -> [Complex] { _fft(array, direction: Complex(0.0, -2.0), scalar: 2) }
private func _fft(_ arr: [Complex], direction: Complex, scalar: Double) -> [Complex] {
guard arr.count > 1 else {
return arr
}
let n = arr.count
let cScalar = Complex(scalar, 0)
precondition(n% 2 == 0, "The Cooley-Tukey FFT algorithm only works when the length of the input is even.")
var (evens, odds) = arr.lazy.enumerated().reduce(into: ([Complex](), [Complex]()), {res, cur in
if cur.offset & 1 == 0 {
res.0.append(cur.element)
} else {
res.1.append(cur.element)
}
})
evens = _fft(evens, direction: direction, scalar: scalar)
odds = _fft(odds, direction: direction, scalar: scalar)
let (left, right) = (0 ..< n / 2).map({i -> (Complex, Complex) in
let offset = (direction * Complex((.pi * Double(i) / Double(n)), 0)).exp * odds[i] / cScalar
let base = evens[i] / cScalar
return (base + offset, base - offset)
}).reduce(into: ([Complex](), [Complex]()), {res, cur in
res.0.append(cur.0)
res.1.append(cur.1)
})
return left + right
}
let dat = [Complex(1.0, 0.0), Complex(1.0, 0.0), Complex(1.0, 0.0), Complex(1.0, 0.0),
Complex(0.0, 0.0), Complex(0.0, 2.0), Complex(0.0, 0.0), Complex(0.0, 0.0)]
print(fft(dat).map({ $0.pretty }))
print(rfft(f).map({ $0.pretty })) | 858Fast Fourier transform
| 17swift
| tvrfl |
(defn fibs []
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1]))) | 862Fibonacci sequence
| 6clojure
| mr7yq |
package main
import "fmt"
func main() {
printFactors(-1)
printFactors(0)
printFactors(1)
printFactors(2)
printFactors(3)
printFactors(53)
printFactors(45)
printFactors(64)
printFactors(600851475143)
printFactors(999999999999999989)
}
func printFactors(nr int64) {
if nr < 1 {
fmt.Println("\nFactors of", nr, "not computed")
return
}
fmt.Printf("\nFactors of%d: ", nr)
fs := make([]int64, 1)
fs[0] = 1
apf := func(p int64, e int) {
n := len(fs)
for i, pp := 0, p; i < e; i, pp = i+1, pp*p {
for j := 0; j < n; j++ {
fs = append(fs, fs[j]*pp)
}
}
}
e := 0
for ; nr & 1 == 0; e++ {
nr >>= 1
}
apf(2, e)
for d := int64(3); nr > 1; d += 2 {
if d*d > nr {
d = nr
}
for e = 0; nr%d == 0; e++ {
nr /= d
}
if e > 0 {
apf(d, e)
}
}
fmt.Println(fs)
fmt.Println("Number of factors =", len(fs))
} | 861Factors of an integer
| 0go
| yg764 |
def factorize = { long target ->
if (target == 1) return [1L]
if (target < 4) return [1L, target]
def targetSqrt = Math.sqrt(target)
def lowfactors = (2L..targetSqrt).grep { (target % it) == 0 }
if (lowfactors == []) return [1L, target]
def nhalf = lowfactors.size() - ((lowfactors[-1] == targetSqrt) ? 1: 0)
[1] + lowfactors + (0..<nhalf).collect { target.intdiv(lowfactors[it]) }.reverse() + [target]
} | 861Factors of an integer
| 7groovy
| f2udn |
import HFM.Primes (primePowerFactors)
import Control.Monad (mapM)
import Data.List (product)
factors = map product .
mapM (\(p,m)-> [p^i | i<-[0..m]]) . primePowerFactors | 861Factors of an integer
| 8haskell
| hs8ju |
my @a = (1, 2, 3, 4, 5, 6);
my @even = grep { $_%2 == 0 } @a; | 853Filter
| 2perl
| jqz7f |
public static TreeSet<Long> factors(long n)
{
TreeSet<Long> factors = new TreeSet<Long>();
factors.add(n);
factors.add(1L);
for(long test = n - 1; test >= Math.sqrt(n); test--)
if(n % test == 0)
{
factors.add(test);
factors.add(n / test);
}
return factors;
} | 861Factors of an integer
| 9java
| 51euf |
$arr = range(1,5);
$evens = array();
foreach ($arr as $val){
if ($val % 2 == 0) $evens[] = $val);
}
print_r($evens); | 853Filter
| 12php
| tvbf1 |
int fib(int n) {
if (n==0 || n==1) {
return n;
}
var prev=1;
var current=1;
for (var i=2; i<n; i++) {
var next = prev + current;
prev = current;
current = next;
}
return current;
}
int fibRec(int n) => n==0 || n==1? n: fibRec(n-1) + fibRec(n-2);
main() {
print(fib(11));
print(fibRec(11));
} | 862Fibonacci sequence
| 18dart
| 8ym0y |
function factors(num)
{
var
n_factors = [],
i;
for (i = 1; i <= Math.floor(Math.sqrt(num)); i += 1)
if (num % i === 0)
{
n_factors.push(i);
if (num / i !== i)
n_factors.push(num / i);
}
n_factors.sort(function(a, b){return a - b;}); | 861Factors of an integer
| 10javascript
| jq07n |
fun printFactors(n: Int) {
if (n < 1) return
print("$n => ")
(1..n / 2)
.filter { n % it == 0 }
.forEach { print("$it ") }
println(n)
}
fun main(args: Array<String>) {
val numbers = intArrayOf(11, 21, 32, 45, 67, 96)
for (number in numbers) printFactors(number)
} | 861Factors of an integer
| 11kotlin
| cjk98 |
values = range(10)
evens = [x for x in values if not x & 1]
ievens = (x for x in values if not x & 1)
evens = filter(lambda x: not x & 1, values) | 853Filter
| 3python
| hs3jw |
function Factors( n )
local f = {}
for i = 1, n/2 do
if n % i == 0 then
f[#f+1] = i
end
end
f[#f+1] = n
return f
end | 861Factors of an integer
| 1lua
| lhbck |
a <- 1:100
evennums <- a[ a%%2 == 0 ]
print(evennums) | 853Filter
| 13r
| ged47 |
ary = [1, 2, 3, 4, 5, 6]
even_ary = ary.select {|elem| elem.even?}
p even_ary
range = 1..6
even_ary = range.select {|elem| elem.even?}
p even_ary | 853Filter
| 14ruby
| b8ykq |
fn main() {
println!("new vec filtered: ");
let nums: Vec<i32> = (1..20).collect();
let evens: Vec<i32> = nums.iter().cloned().filter(|x| x% 2 == 0).collect();
println!("{:?}", evens); | 853Filter
| 15rust
| pombu |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.