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...
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): ...
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:St...
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 Entrop...
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)) ...
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) ...
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....
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 ...
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...
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...
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 ...
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...
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 ...
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 (l...
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 ) } d...
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...
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 (nu...
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; ...
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 ...
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...
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 (!...
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...
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 getEntr...
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 $ tak...
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 ...
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: Comp...
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) -> Fractio...
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) fareySeq...
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) {...
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.le...
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); ...
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( ...
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; }...
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", value...
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__ ...
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 ...
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 (...
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...
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...
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[$_] - ...
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 }...
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 ) { ...
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->i...
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...
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] ...
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...
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 = Comple...
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], ...
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.b...
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(im...
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...
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] == tar...
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(fib...
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