Abusing the System
Statement
Goal
Return the result generated by the given code.Input
First line: The code Language. The names are the same as on the IDE pull-down menu (i.e Bash, C, C#, etc.)
Second line: N, the number of lines of code.
Next N lines: The code.
Second line: N, the number of lines of code.
Next N lines: The code.
Output
The result generated when the code is run.
Constraints
Example
Input
C 19 #include <stdio.h> int main() { int r[100 + 1]; int i,k,b,d,c=0; for (i = 0; i < 100; i++) {r[i] = 2000;} for (k = 70; k > 0; k -= 14) { d=0; i=k; for (;;){ d+=r[i]*10000; b=2*i-1; r[i]=d%b; d/=b; i--; if(i==0) break; d*=i;} if(k==70){printf("%.3f",(float)(c+d/10000)/1000);} else{printf("%.4d",c+d/10000);} c=d%10000;}}
Output
3.1415926535897932384
Tags
Difficulty
Hard
Test cases
C Test
Input
C
19
#include <stdio.h>
int main() {
int r[100 + 1];
int i,k,b,d,c=0;
for (i = 0; i < 100; i++) {r[i] = 2000;}
for (k = 70; k > 0; k -= 14) {
d=0;
i=k;
for (;;){
d+=r[i]*10000;
b=2*i-1;
r[i]=d%b;
d/=b;
i--;
if(i==0) break;
d*=i;}
if(k==70){printf("%.3f",(float)(c+d/10000)/1000);}
else{printf("%.4d",c+d/10000);}
c=d%10000;}}
Output
3.1415926535897932384
C Validator Validator
Input
C
13
#include <stdio.h>
#include <math.h>
#define EPSILON 1.0e-15
int main() {
unsigned long long fact = 1;
double e = 2.0, e0;
int n = 2;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;}
while (fabs(e - e0) >= EPSILON);
printf("%.14f\n", e);}
Output
2.71828182845905
C++ Test
Input
C++
16
#include <algorithm>
#include <iostream>
using namespace std;
void pattern(int n){
int p = 2 * n - 1;
for (int i = 1; i <= p; i++) {
for (int j = 1; j <= p; j++) {
cout << max(abs(i - n), abs(j - n)) + 1 << " ";
}
cout << endl;
}
}
int main(){
int n = 5;
pattern(n);
}
Output
5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5
C++ Validator Validator
Input
C++
36
#include <iostream>
#include <algorithm>
#include <vector>
template <typename Iterator>
size_t prime_sieve(Iterator start, Iterator end){
if (start == end) return 0;
std::fill(start, end, 0);
for (Iterator prime_it = start + 1; prime_it != end; ++prime_it){
if (*prime_it == 1) continue;
size_t stride = (prime_it - start) + 1;
Iterator mark_it = prime_it;
while ((end - mark_it) > stride)
{
std::advance(mark_it, stride);
*mark_it = 1;
}
}
Iterator out_it = start;
for (Iterator it = start + 1; it != end; ++it)
{
if (*it == 0)
{
*out_it = (it - start) + 1;
++out_it;
}
}
return out_it - start;
}
int main(){
std::vector<int> primes(100);
size_t count = prime_sieve(primes.begin(), primes.end());
for (size_t i = 0; i < count; ++i)
std::cout << primes[i] << " ";
std::cout << std::endl;
return 1;
}
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Clojure Test
Input
Clojure
18
(ns example
(:gen-class))
(defn factors [n]
" Find the proper factors of a number "
(into (sorted-set)
(mapcat (fn [x] (if (= x 1) [x] [x (/ n x)]))
(filter #(zero? (rem n %)) (range 1 (inc (Math/sqrt n)))) )))
(def find-pairs (into #{}
(for [n (range 2 20000)
:let [f (factors n) ; Factors of n
M (apply + f) ; Sum of factors
g (factors M) ; Factors of sum
N (apply + g)] ; Sum of Factors of sum
:when (= n N) ; (sum(proDivs(N)) = M and sum(propDivs(M)) = N
:when (not= M N)] ; N not-equal M
(sorted-set n M)))) ; Found pair
(doseq [q find-pairs]
(println q))
Output
#{220 284}
#{6232 6368}
#{1184 1210}
#{5020 5564}
#{2620 2924}
#{12285 14595}
#{17296 18416}
#{10744 10856}
Clojure Validator Validator
Input
Clojure
5
(defn sum-mults [n & mults]
(let [pred (apply some-fn
(map #(fn [x] (zero? (mod x %))) mults))]
(->> (range n) (filter pred) (reduce +))))
(println (sum-mults 1000 3 5))
Output
233168
D Test
Input
D
12
void main(in string[] args){
import std.stdio, std.conv, std.range, std.algorithm, std.exception;
immutable n = args.length == 2 ? args[1].to!uint : 5;
enforce(n > 0 && n % 2 == 1, "Only odd n > 1");
immutable len = text(n ^^ 2).length.text;
foreach (immutable r; 1 .. n + 1){
foreach (immutable c; 1 .. n + 1){
auto a = (n * ((r + c - 1 + (n / 2)) % n)) + ((r + (2 * c) - 2) % n) + 1;
writef("%" ~ len ~ "d%s",a, " ");}
writeln("");
}
}
Output
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
D Validator Validator
Input
D
39
import std.bigint;
import std.math;
import std.stdio;
void fun(ref BigInt a, ref BigInt b, int c) {
auto t = a;
a = b;
b = b * c + t;
}
void solvePell(int n, ref BigInt a, ref BigInt b) {
int x = cast(int) sqrt(cast(real) n);
int y = x;
int z = 1;
int r = x << 1;
BigInt e1 = 1;
BigInt e2 = 0;
BigInt f1 = 0;
BigInt f2 = 1;
while (true) {
y = r * z - y;
z = (n - y * y) / z;
r = (x + y) / z;
fun(e1, e2, r);
fun(f1, f2, r);
a = f2;
b = e2;
fun(b, a, x);
if (a * a - n * b * b == 1) {
return;
}
}
}
void main() {
BigInt x, y;
foreach(n; [61, 109, 181, 277]) {
solvePell(n, x, y);
writefln("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d", n, x, y);
}
}
Output
x^2 - 61 * y^2 = 1 for x = 1766319049 and y = 226153980
x^2 - 109 * y^2 = 1 for x = 158070671986249 and y = 15140424455100
x^2 - 181 * y^2 = 1 for x = 2469645423824185801 and y = 183567298683461940
x^2 - 277 * y^2 = 1 for x = 159150073798980475849 and y = 9562401173878027020
Dart Test
Input
Dart
17
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));
}
Output
[5688, 1, 2844, 2.0, 1896, 3.0, 1422, 4.0, 948, 6.0, 711, 8.0, 632, 9.0, 474, 12.0, 316, 18.0, 237, 24.0, 158, 36.0, 79, 72.0]
Dart Validator Validator
Input
Dart
12
import 'dart:math';
main() {
var nuggets = List<int>.generate(101, (int index) => index);
for (int small in List<int>.generate((100 ~/ (6 + 1)), (int index) => index)) {
for (int medium in List<int>.generate((100 ~/ (9 + 1)), (int index) => index)) {
for (int large in List<int>.generate((100 ~/ (20 + 1)), (int index) => index)) {
nuggets.removeWhere((element) => element == 6 * small + 9 * medium + 20 * large);
}
}
}
print('Largest non-McNuggets number: ${nuggets.reduce(max).toString() ?? 'none'}.');
}
Output
Largest non-McNuggets number: 43.
Bash Test
Input
Bash
10
Num=123
g=$Num
s=0
while [ $Num -gt 0 ]
do
k=$(( $Num % 10 ))
Num=$(( $Num / 10 ))
s=$(( $s + $k ))
done
echo "sum of digits of $g is : $s"
Output
sum of digits of 123 is : 6
Bash Validator Validator
Input
Bash
10
Num=8898
g=$Num
s=0
while [ $Num -gt 0 ]
do
k=$(( $Num % 10 ))
Num=$(( $Num / 10 ))
s=$(( $s + $k ))
done
echo "sum of digits of $g is : $s"
Output
sum of digits of 8898 is : 33
Go Test
Input
Go
30
package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewInt(1)
mp := big.NewInt(0)
bp := big.NewInt(0)
const max = 14
for count, p := 0, uint(2); count < max; {
mp.Lsh(one, p)
mp.Sub(mp, one)
if mp.ProbablyPrime(0) {
fmt.Printf("2 ^ %-4d - 1\n", p)
count++
}
for {
if p > 2 {
p += 2
} else {
p = 3
}
bp.SetUint64(uint64(p))
if bp.ProbablyPrime(0) {
break
}
}
}
}
Output
2 ^ 2 - 1
2 ^ 3 - 1
2 ^ 5 - 1
2 ^ 7 - 1
2 ^ 13 - 1
2 ^ 17 - 1
2 ^ 19 - 1
2 ^ 31 - 1
2 ^ 61 - 1
2 ^ 89 - 1
2 ^ 107 - 1
2 ^ 127 - 1
2 ^ 521 - 1
2 ^ 607 - 1
Go Validator Validator
Input
Go
28
package main
import "fmt"
func countDivisors(n int) int {
if n < 2 {
return 1
}
count := 2 // 1 and n
for i := 2; i <= n/2; i++ {
if n%i == 0 {
count++
}
}
return count
}
func main() {
fmt.Println("The first 20 anti-primes are:")
maxDiv := 0
count := 0
for n := 1; count < 20; n++ {
d := countDivisors(n)
if d > maxDiv {
fmt.Printf("%d ", n)
maxDiv = d
count++
}
}
fmt.Println()
}
Output
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
Groovy Test
Input
Groovy
37
class Answer{ public static boolean find(int x)
{
int sum = 0,temp,var;
var = x;
while(x>0)
{
temp = x%10;
sum = sum + temp;
x = x/10;
}
if(var%sum==0) temp = 1;
else temp = 0;
return temp;
}
public static void main(String[] args)
{
int t,i;
t = 0;
for(i=1;t<20;i++)
{
if(find(i))
{
print(i + " ");
t++;
}
}
int x = 0;
int y = 1000;
while(x!=1)
{
if(find(y)) x = 1;
y++;
}
println();
println(y+1);
}
}
Output
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42
1002
Groovy Validator Validator
Input
Groovy
30
static boolean isPrime(long x) {
if (x < 2) return false
if (x == 2) return true
if ((x & 1) == 0) return false
for (long i = 3; i <= Math.sqrt(x); i += 2) {
if (x % i == 0) return false
}
return true
}
static boolean isEmirp(long x) {
String xString = Long.toString(x)
if (xString.length() == 1) return false
if (xString.matches("[24568].*") || xString.matches(".*[24568]")) return false //eliminate some easy rejects
long xR = Long.parseLong(new StringBuilder(xString).reverse().toString())
if (xR == x) return false
return isPrime(x) && isPrime(xR)
}
static void main(String[] args) {
int count = 0
long x = 1
println("First 20 emirps:")
while (count < 20) {
if (isEmirp(x)) {
count++
print(x + " ")
}
x++
}
}
Output
First 20 emirps:
13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Haskell Test
Input
Haskell
43
import Data.List (sort)
import Control.Arrow ((&&&))
-- VAMPIRE NUMBERS ------------------------------------------------------------
vampires :: [Int]
vampires = filter (not . null . fangs) [1 ..]
fangs :: Int -> [(Int, Int)]
fangs n
| odd w = []
| otherwise = ((,) <*> quot n) <$> filter isfang (integerFactors n)
where
ndigit :: Int -> Int
ndigit 0 = 0
ndigit n = 1 + ndigit (quot n 10)
w = ndigit n
xmin = 10 ^ (quot w 2 - 1)
xmax = xmin * 10
isfang x =
x > xmin &&
x < y &&
y < xmax && -- same length
(quot x 10 /= 0 || quot y 10 /= 0) && -- not zero-ended
sort (show n) == sort (show x ++ show y)
where
y = quot n x
integerFactors :: Int -> [Int]
integerFactors n
| n < 1 = []
| otherwise =
lows ++
(quot n <$>
(if intSquared == n -- A perfect square,
then tail -- and cofactor of square root would be redundant.
else id)
(reverse lows))
where
(intSquared, lows) =
(^ 2) &&& (filter ((0 ==) . rem n) . enumFromTo 1) $
floor (sqrt $ fromIntegral n)
main :: IO [()]
main =
mapM
(print . ((,) <*>) fangs)
(take 15 vampires)
Output
(1260,[(21,60)])
(1395,[(15,93)])
(1435,[(35,41)])
(1530,[(30,51)])
(1827,[(21,87)])
(2187,[(27,81)])
(6880,[(80,86)])
(102510,[(201,510)])
(104260,[(260,401)])
(105210,[(210,501)])
(105264,[(204,516)])
(105750,[(150,705)])
(108135,[(135,801)])
(110758,[(158,701)])
(115672,[(152,761)])
Haskell Validator Validator
Input
Haskell
7
sierpinski 0 = ["*"]
sierpinski n = map ((space ++) . (++ space)) down ++
map (unwords . replicate 2) down
where down = sierpinski (n - 1)
space = replicate (2 ^ (n - 1)) ' '
main = mapM_ putStrLn $ sierpinski 4
Output
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Java Test
Input
Java
14
class Solution {
public static boolean isPali(String x){
return x.equals(new StringBuilder(x).reverse().toString());
}
public static void main(String[] args){
for(long i = 0, count = 0; count < 4;i++){
if((i & 1) == 0 && (i != 0)) continue;
if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){
System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3));
count++;
}
}
}
}
Output
0, 0, 0
1, 1, 1
6643, 1100111110011, 100010001
1422773, 101011011010110110101, 2200021200022
Java Validator Validator
Input
Java
23
import java.util.HashMap;
import java.util.Map;
class Solution {
public static void main(String[] args) {
System.out.println("First 10 terms of Van Eck's sequence:");
vanEck(1, 10);
}
private static void vanEck(int firstIndex, int lastIndex) {
Map<Integer,Integer> vanEckMap = new HashMap<>();
int last = 0;
if ( firstIndex == 1 ) {
System.out.printf("VanEck[%d] = %d%n", 1, 0);
}
for ( int n = 2 ; n <= lastIndex ; n++ ) {
int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;
vanEckMap.put(last, n);
last = vanEck;
if ( n >= firstIndex ) {
System.out.printf("VanEck[%d] = %d%n", n, vanEck);
}
}
}
}
Output
First 10 terms of Van Eck's sequence:
VanEck[1] = 0
VanEck[2] = 0
VanEck[3] = 1
VanEck[4] = 0
VanEck[5] = 2
VanEck[6] = 0
VanEck[7] = 2
VanEck[8] = 2
VanEck[9] = 1
VanEck[10] = 6
JavaScript Test
Input
JavaScript
17
function toRoman(num) {
return 'I'
.repeat(num)
.replace(/IIIII/g, 'V')
.replace(/VV/g, 'X')
.replace(/XXXXX/g, 'L')
.replace(/LL/g, 'C')
.replace(/CCCCC/g, 'D')
.replace(/DD/g, 'M')
.replace(/VIIII/g, 'IX')
.replace(/LXXXX/g, 'XC')
.replace(/XXXX/g, 'XL')
.replace(/DCCCC/g, 'CM')
.replace(/CCCC/g, 'CD')
.replace(/IIII/g, 'IV');
}
console.log(toRoman(2266));
Output
MMCCLXVI
JavaScript Validator Validator
Input
JavaScript
17
function toRoman(num) {
return 'I'
.repeat(num)
.replace(/IIIII/g, 'V')
.replace(/VV/g, 'X')
.replace(/XXXXX/g, 'L')
.replace(/LL/g, 'C')
.replace(/CCCCC/g, 'D')
.replace(/DD/g, 'M')
.replace(/VIIII/g, 'IX')
.replace(/LXXXX/g, 'XC')
.replace(/XXXX/g, 'XL')
.replace(/DCCCC/g, 'CM')
.replace(/CCCC/g, 'CD')
.replace(/IIII/g, 'IV');
}
console.log(toRoman(2466));
Output
MMCDLXVI
Lua Test
Input
Lua
15
local function permutation(a, n, cb)
if n == 0 then
cb(a)
else
for i = 1, n do
a[i], a[n] = a[n], a[i]
permutation(a, n - 1, cb)
a[i], a[n] = a[n], a[i]
end
end
end
local function callback(a)
print('{'..table.concat(a, ', ')..'}')
end
permutation({1,2,3}, 3, callback)
Output
{2, 3, 1}
{3, 2, 1}
{3, 1, 2}
{1, 3, 2}
{2, 1, 3}
{1, 2, 3}
Lua Validator Validator
Input
Lua
19
-- Return farey sequence of order n
function farey (n)
local a, b, c, d, k = 0, 1, 1, n
local farTab = {{a, b}}
while c <= n do
k = math.floor((n + b) / d)
a, b, c, d = c, d, k * c - a, k * d - b
table.insert(farTab, {a, b})
end
return farTab
end
-- Main procedure
for i = 1, 8 do
io.write(i .. ": ")
for _, frac in pairs(farey(i)) do io.write(frac[1] .. "/" .. frac[2] .. " ") end
print()
end
for i = 100, 1000, 100 do print(i .. ": " .. #farey(i) .. " items") end
Output
1: 0/1 1/1
2: 0/1 1/2 1/1
3: 0/1 1/3 1/2 2/3 1/1
4: 0/1 1/4 1/3 1/2 2/3 3/4 1/1
5: 0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1
6: 0/1 1/6 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 5/6 1/1
7: 0/1 1/7 1/6 1/5 1/4 2/7 1/3 2/5 3/7 1/2 4/7 3/5 2/3 5/7 3/4 4/5 5/6 6/7 1/1
8: 0/1 1/8 1/7 1/6 1/5 1/4 2/7 1/3 3/8 2/5 3/7 1/2 4/7 3/5 5/8 2/3 5/7 3/4 4/5 5/6 6/7 7/8 1/1
100: 3045 items
200: 12233 items
300: 27399 items
400: 48679 items
500: 76117 items
600: 109501 items
700: 149019 items
800: 194751 items
900: 246327 items
1000: 304193 items
OCaml Test
Input
OCaml
32
let minimum a b c =
min a (min b c)
let levenshtein_distance s t =
let m = String.length s
and n = String.length t in
let d = Array.make_matrix (m+1) (n+1) 0 in
for i = 0 to m do
d.(i).(0) <- i
done;
for j = 0 to n do
d.(0).(j) <- j
done;
for j = 1 to n do
for i = 1 to m do
if s.[i-1] = t.[j-1] then
d.(i).(j) <- d.(i-1).(j-1)
else
d.(i).(j) <- minimum
(d.(i-1).(j) + 1)
(d.(i).(j-1) + 1)
(d.(i-1).(j-1) + 1)
done;
done;
d.(m).(n)
;;
let test s t =
Printf.printf " %s -> %s = %d\n" s t (levenshtein_distance s t);
;;
let () =
test "kitten" "sitting";
test "rosettacode" "raisethysword";
;;
Output
kitten -> sitting = 3
rosettacode -> raisethysword = 8
OCaml Validator Validator
Input
OCaml
17
module ISet = Set.Make(struct type t = int let compare=compare end)
let pq = ref (ISet.singleton 1)
let next () =
let m = ISet.min_elt !pq in
pq := ISet.(remove m !pq |> add (2*m) |> add (3*m) |> add (5*m));
m
let () =
print_string "The first 20 are: ";
for i = 1 to 20
do
Printf.printf "%d " (next ())
done;
for i = 21 to 1690
do
ignore (next ())
done;
Printf.printf "\nThe 1691st is %d\n" (next ());
Output
The first 20 are: 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36
The 1691st is 2125764000
Pascal Test
Input
Pascal
19
program PerfectNumbers;
function isPerfect(number: longint): boolean;
var
i, sum: longint;
begin
sum := 1;
for i := 2 to round(sqrt(real(number))) do
if (number mod i = 0) then
sum := sum + i + (number div i);
isPerfect := (sum = number);
end;
var
candidate: longint;
begin
writeln('Perfect numbers from 1 to 335503:');
for candidate := 2 to 335503 do
if isPerfect(candidate) then
writeln (candidate, ' is a perfect number.');
end.
Output
Perfect numbers from 1 to 335503:
6 is a perfect number.
28 is a perfect number.
496 is a perfect number.
8128 is a perfect number.
Pascal Validator Validator
Input
Pascal
64
Program zigzag( input, output );
const
size = 5;
var
zzarray: array [1..size, 1..size] of integer;
element, i, j: integer;
direction: integer;
width, n: integer;
begin
i := 1;
j := 1;
direction := 1;
for element := 0 to (size*size) - 1 do
begin
zzarray[i,j] := element;
i := i + direction;
j := j - direction;
if (i = 0) then
begin
direction := -direction;
i := 1;
if (j > size) then
begin
j := size;
i := 2;
end;
end
else if (i > size) then
begin
direction := -direction;
i := size;
j := j + 2;
end
else if (j = 0) then
begin
direction := -direction;
j := 1;
if (i > size) then
begin
j := 2;
i := size;
end;
end
else if (j > size) then
begin
direction := -direction;
j := size;
i := i + 2;
end;
end;
width := 2;
n := size;
while (n > 0) do
begin
width := width + 1;
n := n div 10;
end;
for j := 1 to size do
begin
for i := 1 to size do
write(zzarray[i,j]:width);
writeln;
end;
end.
Output
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Perl Test Test
Input
Perl
7
sub fact {
my $n = shift;
$n == 0 ? 1 : $n*fact($n-1);
}
foreach my $i (0..16) {
print "$i! = ", fact($i), "\n";
}
Output
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
Perl Validator Validator
Input
Perl
8
sub fibonacci {
my $n = shift;
$n < 3 ? 1 : fibonacci($n-1) + fibonacci($n-2)
}
foreach (1..16) {
print fibonacci($_), ", ";
}
print "..."
Output
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...
PHP Test
Input
PHP
35
<?php
function is_prime($n, $k) {
if ($n == 2)
return true;
if ($n < 2 || $n % 2 == 0)
return false;
$d = $n - 1;
$s = 0;
while ($d % 2 == 0) {
$d /= 2;
$s++;
}
for ($i = 0; $i < $k; $i++) {
$a = rand(2, $n-1);
$x = bcpowmod($a, $d, $n);
if ($x == 1 || $x == $n-1)
continue;
for ($j = 1; $j < $s; $j++) {
$x = bcmod(bcmul($x, $x), $n);
if ($x == 1)
return false;
if ($x == $n-1)
continue 2;
}
return false;
}
return true;
}
for ($i = 1; $i <= 50; $i++)
if (is_prime($i, 10))
echo "$i, ";
echo "\n";
?>
Output
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
PHP Validator Validator
Input
PHP
21
<?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
Output
1
3435
Python 3 Test
Input
Python3
17
def bellTriangle(n):
tri = [None] * n
for i in range(n):
tri[i] = [0] * i
tri[1][0] = 1
for i in range(2, n):
tri[i][0] = tri[i - 1][i - 2]
for j in range(1, i):
tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1]
return tri
def main():
bt = bellTriangle(51)
print("First fifteen Bell numbers:")
for i in range(1, 16):
print("%2d: %d" % (i, bt[i][0]))
main()
Output
First fifteen Bell numbers:
1: 1
2: 1
3: 2
4: 5
5: 15
6: 52
7: 203
8: 877
9: 4140
10: 21147
11: 115975
12: 678570
13: 4213597
14: 27644437
15: 190899322
Python 3 Validator Validator
Input
Python3
25
def prime_factors(m=2):
for i in range(2, m):
r, q = divmod(m, i)
if not q:
return [i] + prime_factors(r)
return [m]
def k_almost_primes(n, k=2):
multiples = set()
lists = list()
for x in range(k+1):
lists.append([])
for i in range(2, n+1):
if i not in multiples:
if len(lists[1]) < 10:
lists[1].append(i)
multiples.update(range(i*i, n+1, i))
print("k=1: {}".format(lists[1]))
for j in range(2, k+1):
for m in multiples:
l = prime_factors(m)
ll = len(l)
if ll == j and len(lists[j]) < 10:
lists[j].append(m)
print("k={}: {}".format(j, lists[j]))
k_almost_primes(200, 5)
Output
k=1: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
k=2: [4, 6, 9, 10, 14, 15, 21, 22, 25, 26]
k=3: [8, 12, 18, 20, 27, 28, 30, 42, 44, 45]
k=4: [16, 24, 36, 40, 54, 56, 60, 81, 84, 88]
k=5: [32, 48, 72, 80, 108, 112, 120, 162, 168, 176]
Ruby Test
Input
Ruby
11
require "prime"
class Integer
def smith?
return false if prime?
digits.sum == prime_division.map{|pr,n| pr.digits.sum * n}.sum
end
end
n = 10_000
res = 1.upto(n).select(&:smith?)
puts "#{res.size} smith numbers below #{n}:
#{res.first(5).join(", ")},... #{res.last(5).join(", ")}"
Output
376 smith numbers below 10000:
4, 22, 27, 58, 85,... 9924, 9942, 9968, 9975, 9985
Ruby Validator Validator
Input
Ruby
22
Zero = proc { |f| proc { |x| x } }
Succ = proc { |n| proc { |f| proc { |x| f[n[f][x]] } } }
Add = proc { |n, m| proc { |f| proc { |x| m[f][n[f][x]] } } }
Mult = proc { |n, m| proc { |f| proc { |x| m[n[f]][x] } } }
Power = proc { |b, e| e[b] }
ToInt = proc { |f| countup = proc { |i| i+1 }; f[countup][0] }
FromInt = proc { |x|
countdown = proc { |i|
case i
when 0 then Zero
else Succ[countdown[i-1]]
end
}
countdown[x]
}
Three = Succ[Succ[Succ[Zero]]]
Four = FromInt[4]
puts [ Add[Three, Four],
Mult[Three, Four],
Power[Three, Four],
Power[Four, Three] ].map(&ToInt)
Output
7
12
81
64
Rust Test
Input
Rust
49
struct DivisorGen {
curr: u64,
last: u64,
}
impl Iterator for DivisorGen {
type Item = u64;
fn next(&mut self) -> Option<u64> {
self.curr += 2u64;
if self.curr < self.last{
None
} else {
Some(self.curr)
}
}
}
fn divisor_gen(num : u64) -> DivisorGen {
DivisorGen { curr: 0u64, last: (num / 2u64) + 1u64 }
}
fn is_prime(num : u64) -> bool{
if num == 2 || num == 3 {
return true;
} else if num % 2 == 0 || num % 3 == 0 || num <= 1{
return false;
}else{
for i in divisor_gen(num){
if num % i == 0{
return false;
}
}
}
return true;
}
fn main() {
let fermat_closure = |i : u32| -> u64 {2u64.pow(2u32.pow(i + 1u32))};
let mut f_numbers : Vec<u64> = Vec::new();
println!("First 4 Fermat numbers:");
for i in 0..4 {
let f = fermat_closure(i) + 1u64;
f_numbers.push(f);
println!("F{}: {}", i, f);
}
println!("Factor of the first four numbers:");
for f in f_numbers.iter(){
let is_prime : bool = f % 4 == 1 && is_prime(*f);
let not_or_not = if is_prime {" "} else {" not "};
println!("{} is{}prime", f, not_or_not);
}
}
Output
First 4 Fermat numbers:
F0: 5
F1: 17
F2: 257
F3: 65537
Factor of the first four numbers:
5 is prime
17 is prime
257 is prime
65537 is prime
Rust Validator Validator
Input
Rust
25
use std::collections::BTreeSet;
fn powerset<T: Ord + Clone>(mut set: BTreeSet<T>) -> BTreeSet<BTreeSet<T>> {
if set.is_empty() {
let mut powerset = BTreeSet::new();
powerset.insert(set);
return powerset;
}
let entry = set.iter().nth(0).unwrap().clone();
set.remove(&entry);
let mut powerset = powerset(set);
for mut set in powerset.clone().into_iter() {
set.insert(entry.clone());
powerset.insert(set);
}
powerset
}
fn main() {
let set = (1..5).collect();
let set = powerset(set);
println!("{:?}", set);
let set = ["a", "b", "c"].iter().collect();
let set = powerset(set);
println!("{:?}", set);
}
Output
{{}, {1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 4}, {1, 3}, {1, 3, 4}, {1, 4}, {2}, {2, 3}, {2, 3, 4}, {2, 4}, {3}, {3, 4}, {4}}
{{}, {"a"}, {"a", "b"}, {"a", "b", "c"}, {"a", "c"}, {"b"}, {"b", "c"}, {"c"}}
Scala Test
Input
Scala
1
object Solution extends App {println("xsxsxsxs")}
Output
xsxsxsxs
Scala Validator Validator
Input
Scala
1
object Solution extends App {println("zzzzzz")}
Output
zzzzzz
Swift Test
Input
Swift
17
extension BinaryInteger {
@inlinable
public var isNarcissistic: Bool {
let digits = String(self).map({ Int(String($0))! })
let m = digits.count
guard m != 1 else {
return true
}
return digits.map({ $0.power(m) }).reduce(0, +) == self
}
@inlinable
public func power(_ n: Self) -> Self {
return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *)
}
}
let narcs = Array((0...).lazy.filter({ $0.isNarcissistic }).prefix(15))
print("First 15 narcissistic numbers are \(narcs)")
Output
First 15 narcissistic numbers are [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634]
Swift Validator Validator
Input
Swift
11
func multiFactorial(_ n: Int, k: Int) -> Int {
return stride(from: n, to: 0, by: -k).reduce(1, *)
}
let multis = (1...5).map({degree in
(1...10).map({member in
multiFactorial(member, k: degree)
})
})
for (i, degree) in multis.enumerated() {
print("Degree \(i + 1): \(degree)")
}
Output
Degree 1: [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
Degree 2: [1, 2, 3, 8, 15, 48, 105, 384, 945, 3840]
Degree 3: [1, 2, 3, 4, 10, 18, 28, 80, 162, 280]
Degree 4: [1, 2, 3, 4, 5, 12, 21, 32, 45, 120]
Degree 5: [1, 2, 3, 4, 5, 6, 14, 24, 36, 50]
TypeScript Test
Input
TypeScript
14
function mean(numbersArr)
{
let arrLen = numbersArr.length;
if (arrLen > 0) {
let sum = 0;
for (let i of numbersArr) {
sum += i;
}
return sum/arrLen;
}
else return "Not defined";
}
console.log( mean( [1,2,3,4,5] ) );
console.log( mean( [] ) );
Output
3
Not defined
TypeScript Validator Validator
Input
TypeScript
11
const isLongYear = (year)=> {
const jan1 = new Date(year, 0, 1);
const dec31 = new Date(year, 11, 31);
return (4 == jan1.getDay() || 4 == dec31.getDay())
}
for (let y = 1995; y <= 2045; y++) {
if (isLongYear(y)) {
console.log(y)
}
}
Output
1998
2004
2009
2015
2020
2026
2032
2037
2043
Objective-C Test
Input
Objective-C
24
#include <Foundation/Foundation.h>
#define CACHE 256
enum { h_unknown = 0, h_yes, h_no };
unsigned char buf[CACHE] = {0, h_yes, 0};
int happy(int n){
int sum = 0, x, nn;
if (n < CACHE) {
if (buf[n]) return 2 - buf[n];
buf[n] = h_no;
}
for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;
x = happy(sum);
if (n < CACHE) buf[n] = 2 - x;
return x;
}
int main(){
int i, cnt = 8;
for (i = 1; cnt || !printf("\n"); i++)
if (happy(i)) --cnt, printf("%d ", i);
printf("The %dth happy number: ", cnt = 1000000);
for (i = 1; cnt; i++)
if (happy(i)) --cnt || printf("%d\n", i);
return 0;
}
Output
1 7 10 13 19 23 28 31
The 1000000th happy number: 7105849
Objective-C Validator Validator
Input
Objective-C
16
#include <Foundation/Foundation.h>
void move(int n, int from, int via, int to)
{
if (n > 1) {
move(n - 1, from, to, via);
printf("Move disk from pole %d to pole %d\n", from, to);
move(n - 1, via, from, to);
} else {
printf("Move disk from pole %d to pole %d\n", from, to);
}
}
int main()
{
move(4, 1,2,3);
return 0;
}
Output
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 3 to pole 1
Move disk from pole 3 to pole 2
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Move disk from pole 2 to pole 1
Move disk from pole 3 to pole 1
Move disk from pole 2 to pole 3
Move disk from pole 1 to pole 2
Move disk from pole 1 to pole 3
Move disk from pole 2 to pole 3
Solution language
Solution
Stub generator input