task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #11l | 11l | F pow_mod(BigInt =base, BigInt =exponent, BigInt modulus)
BigInt result = 1
L exponent != 0
I exponent % 2 != 0
result = (result * base) % modulus
exponent I/= 2
base = (base * base) % modulus
R result
print(pow_mod(BigInt(‘298834816205857413691589142149881946632016331292695242... |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaysty... | #C | C | #include <stdio.h>
struct ModularArithmetic {
int value;
int modulus;
};
struct ModularArithmetic make(const int value, const int modulus) {
struct ModularArithmetic r = { value % modulus, modulus };
return r;
}
struct ModularArithmetic add(const struct ModularArithmetic a, const struct ModularAri... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #CLU | CLU | digit_sum = proc (n: int) returns (int)
sum: int := 0
while n > 0 do
sum := sum + n // 10
n := n / 10
end
return(sum)
end digit_sum
a131382 = iter () yields (int)
n: int := 1
while true do
m: int := 1
while digit_sum(m * n) ~= n do
m := m + 1
... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. A131382.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARIABLES.
03 MAXIMUM PIC 99 VALUE 40.
03 N PIC 999.
03 M PIC 9(9).
03 N-TIMES-M PIC 9(9).
03 DIGITS PIC 9 O... |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfect... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
public static class MinimalSteps
{
public static void Main() {
var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 });
var lookup = CreateLookup(2_000, divisors, subtractors);
Console.WriteLine($"Divisors: [{divis... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Swift | Swift |
let maxn = 31
func nq(n: Int) -> Int {
var cols = Array(repeating: 0, count: maxn)
var diagl = Array(repeating: 0, count: maxn)
var diagr = Array(repeating: 0, count: maxn)
var posibs = Array(repeating: 0, count: maxn)
var num = 0
for q0 in 0...n-3 {
for q1 in q0+2...n-1 {
le... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[InverseMinkowskiQuestionMark]
InverseMinkowskiQuestionMark[val_] := Module[{x}, (x /. FindRoot[MinkowskiQuestionMark[x] == val, {x, Floor[val], Ceiling[val]}])]
MinkowskiQuestionMark[GoldenRatio]
InverseMinkowskiQuestionMark[-5/9] // RootApproximant
MinkowskiQuestionMark[InverseMinkowskiQuestionMark[0.12131415... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #Nim | Nim | import math, strformat
const MaxIter = 151
func minkowski(x: float): float =
if x notin 0.0..1.0:
return floor(x) + minkowski(x - floor(x))
var
p = x.uint64
r = p + 1
q, s = 1u64
d = 1.0
y = p.float
while true:
d /= 2
if y + d == y: break
let m = p + r
if m < 0 ... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Standard_ML | Standard ML | fun f 0 = 1
| f n = n - m (f (n-1))
and m 0 = 0
| m n = n - f (m (n-1))
; |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Transact_SQL | Transact SQL |
---- BEGIN ------------
create table MONTY_HALL(
NOE int,
CAR int,
ALTERNATIVE int,
ORIGIN int,
[KEEP] int,
[CHANGE] int,
[RANDOM] int
)
-- INIT
truncate table MONTY_HALL
declare @N int , @i int -- No of Experiments and their counter
declare @rooms int , -- number of rooms
@origin int... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Microsoft_Small_Basic | Microsoft Small Basic |
n = 12
For j = 1 To n - 1
TextWindow.CursorLeft = (j - 1) * 4 + (3 - Text.GetLength(j))
TextWindow.Write(j)
TextWindow.Write(" ")
EndFor
TextWindow.CursorLeft = (n - 1) * 4 + (3 - Text.GetLength(n))
TextWindow.Write(n)
TextWindow.WriteLine("")
For j = 0 To n - 1
TextWindow.Write("----")
EndFor
TextWindow.Writ... |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Julia | Julia | using UnicodePlots
modifier(x) = (y = 2x - 1; y < 0 ? -y : y)
modrands(rands1, rands2) = [x for (i, x) in enumerate(rands1) if rands2[i] < modifier(x)]
histogram(modrands(rand(50000), rand(50000)), nbins = 20)
|
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[Modifier, CreateRandomNumber]
Modifier[x_] := If[x < 0.5, 2 (0.5 - x), 2 (x - 0.5)]
CreateRandomNumber[] := Module[{r1, r2, done = True},
While[done,
r1 = RandomReal[];
r2 = RandomReal[];
If[r2 < Modifier[r1],
Return[r1];
done = False
]
]
]
numbers = Table[CreateRandomNumber[], 1000... |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Nim | Nim | import random, strformat, strutils, sugar
type ValRange = range[0.0..1.0]
func modifier(x: ValRange): ValRange =
if x < 0.5: 2 * (0.5 - x) else: 2 * (x - 0.5)
proc rand(modifier: (float) -> float): ValRange =
while true:
let r1 = rand(1.0)
let r2 = rand(1.0)
if r2 < modifier(r1):
return r1
... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #Ada | Ada | with Ada.Text_IO, Ada.Command_Line, Crypto.Types.Big_Numbers;
procedure Mod_Exp is
A: String :=
"2988348162058574136915891421498819466320163312926952423791023078876139";
B: String :=
"2351399303373464486466122544523690094744975233415544072992656881240319";
D: constant Positive := Positive'Max(P... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #ALGOL_68 | ALGOL 68 |
BEGIN
PR precision=1000 PR
MODE LLI = LONG LONG INT; CO For brevity CO
PROC mod power = (LLI base, exponent, modulus) LLI :
BEGIN
LLI result := 1, b := base, e := exponent;
IF exponent < 0
THEN
put (stand error, (("Negative exponent", exponent, newline)))
ELSE
WHILE e > 0
DO... |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaysty... | #C.23 | C# | using System;
namespace ModularArithmetic {
interface IAddition<T> {
T Add(T rhs);
}
interface IMultiplication<T> {
T Multiply(T rhs);
}
interface IPower<T> {
T Power(int pow);
}
interface IOne<T> {
T One();
}
class ModInt : IAddition<ModInt>, IMul... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Cowgol | Cowgol | include "cowgol.coh";
sub digit_sum(n: uint32): (sum: uint8) is
sum := 0;
while n != 0 loop
sum := sum + (n % 10) as uint8;
n := n / 10;
end loop;
end sub;
sub a131382(n: uint8): (m: uint32) is
m := 1;
while n != digit_sum(n as uint32 * m) loop
m := m + 1;
end loop;
e... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Draco | Draco | /* this is very slow even in emulation - if you're going to try it
* on a real 8-bit micro I'd recommend setting this back to 40;
* it does, however, eventually get there */
byte MAX = 70;
/* note on types: 2^32 is a 10-digit number,
* so the digit sum of an ulong is guaranteed
* to be <= 90 */
proc nonrec digits... |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfect... | #FreeBASIC | FreeBASIC | Dim Shared As Integer minPasos 'minimal number of steps to get to 1
Dim Shared As Integer Subtractor '1 or 2
Dim Shared As Integer Ns(20000), Ops(20000), MinNs(20000), MinOps(20000)
Sub Reduce(N As Integer, Paso As Integer) 'Reduce N to 1, recording minimum steps
If N = 1 Then
If Paso < minPasos... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #SystemVerilog | SystemVerilog | program N_queens;
parameter SIZE_LOG2 = 3;
parameter SIZE = 1 << SIZE_LOG2;
`define ABS_DIFF(a,b) (a>b?a-b:b-a)
class board;
rand bit [SIZE_LOG2-1:0] row[SIZE];
constraint rook_moves {
foreach (row[i]) foreach (row[j]) if (i < j) {
row[i] != row[j];
}
}
constraint d... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use POSIX qw(floor);
my $MAXITER = 50;
sub minkowski {
my($x) = @_;
return floor($x) + minkowski( $x - floor($x) ) if $x > 1 || $x < 0 ;
my $y = my $p = floor($x);
my ($q,$s,$d) = (1,1,1);
my $r = $p + 1;
while () {
last if ( $y + ($... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Swift | Swift | func F(n: Int) -> Int {
return n == 0 ? 1 : n - M(F(n-1))
}
func M(n: Int) -> Int {
return n == 0 ? 0 : n - F(M(n-1))
}
for i in 0..20 {
print("\(F(i)) ")
}
println()
for i in 0..20 {
print("\(M(i)) ")
}
println() |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #UNIX_Shell | UNIX Shell | #!/bin/bash
# Simulates the "monty hall" probability paradox and shows results.
# http://en.wikipedia.org/wiki/Monty_Hall_problem
# (should rewrite this in C for faster calculating of huge number of rounds)
# (Hacked up by Éric Tremblay, 07.dec.2010)
num_rounds=10 #default number of rounds
num_doors=3 # default numbe... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П0 КИП0 КИП4 КИП5 ИП4 ИП5 * С/П
ИП5 ИП0 - x=0 03
ИП4 ИП0 - x#0 22 ИП4 П5 БП 02
С/П |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Perl | Perl | use strict;
use warnings;
use List::Util 'max';
sub distribution {
my %param = ( function => \&{scalar sub {return 1}}, sample_size => 1e5, @_);
my @values;
do {
my($r1, $r2) = (rand, rand);
push @values, $r1 if &{$param{function}}($r1) > $r2;
} until @values == $param{sample_size};
... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #Arturo | Arturo | a: 2988348162058574136915891421498819466320163312926952423791023078876139
b: 2351399303373464486466122544523690094744975233415544072992656881240319
loop [40 80 180 888] 'm ->
print ["(a ^ b) % 10 ^" m "=" powmod a b 10^m] |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #AutoHotkey | AutoHotkey | #NoEnv
#SingleInstance, Force
SetBatchLines, -1
#Include mpl.ahk
MP_SET(base, "2988348162058574136915891421498819466320163312926952423791023078876139")
, MP_SET(exponent, "2351399303373464486466122544523690094744975233415544072992656881240319")
, MP_SET(modulus, "10000000000000000000000000000000000000000")
, NumG... |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaysty... | #C.2B.2B | C++ | #include <iostream>
#include <ostream>
template<typename T>
T f(const T& x) {
return (T) pow(x, 100) + x + 1;
}
class ModularInteger {
private:
int value;
int modulus;
void validateOp(const ModularInteger& rhs) const {
if (modulus != rhs.modulus) {
throw std::runtime_error("Lef... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #F.23 | F# |
// Minimum multiple of m where digital sum equals m. Nigel Galloway: January 31st., 2022
let SoD n=let rec SoD n=function 0L->int n |g->SoD(n+g%10L)(g/10L) in SoD 0L n
let A131382(g:int)=let rec fN i=match SoD(i*int64(g)) with
n when n=g -> i
|n when n>... |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfect... | #Go | Go | package main
import (
"fmt"
"strings"
)
const limit = 50000
var (
divs, subs []int
mins [][]string
)
// Assumes the numbers are presented in order up to 'limit'.
func minsteps(n int) {
if n == 1 {
mins[1] = []string{}
return
}
min := limit
var p, q int
v... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Tailspin | Tailspin |
templates queens
def n: $;
templates addColumn
def prev: $;
templates addIfPossible
def row: $;
def minor: $ - $prev::length - 1;
def major: $ + $prev::length + 1;
// If prev is not an array that contains row, send it on...
$prev -> \(when <~[<=$row>]> do $ !\)
->... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #Phix | Phix | with javascript_semantics
constant MAXITER = 151
function minkowski(atom x)
atom p = floor(x)
if x>1 or x<0 then return p+minkowski(x-p) end if
atom q = 1, r = p + 1, s = 1, m, n, d = 1, y = p
while true do
d = d/2
if y + d = y then exit end if
m = p + r
if m < 0 or p <... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Symsyn | Symsyn |
F param Fn
if Fn = 0
1 R
else
(Fn-1) nm1
save Fn
call F nm1
result Fr
save Fr
call M Fr
result Mr
restore Fr
restore Fn
(Fn-Mr) R
endif
return R
M param Mn
if Mn = 0
0 R
else
(Mn-1) nm1
save Mn
call M nm1
result Mr
sav... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Ursala | Ursala | #import std
#import nat
#import flo
rounds = 10000
car_locations = arc{1,2,3}* iota rounds
initial_choices = arc{1,2,3}* iota rounds
staying_wins = length (filter ==) zip(car_locations,initial_choices)
switching_wins = length (filter ~=) zip(car_locations,initial_choices)
format = printf/'%0.2f'+ (times\100... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Vedit_macro_language | Vedit macro language | #90 = Time_Tick // seed for random number generator
#91 = 3 // random numbers in range 0 to 2
#1 = 0 // wins for "always stay" strategy
#2 = 0 // wins for "always switch" strategy
for (#10 = 0; #10 < 10000; #10++) { // 10,000 iterations
Call("RANDOM")
#3 = Return_Value // #3 = winning door
Cal... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Modula-2 | Modula-2 |
MODULE MultiplicationTables;
FROM SWholeIO IMPORT
WriteInt;
FROM STextIO IMPORT
WriteString, WriteLn;
CONST
N = 12;
VAR
I, J: INTEGER;
BEGIN
FOR J := 1 TO N - 1 DO
WriteInt(J, 3);
WriteString(" ");
END;
WriteInt(N, 3);
WriteLn;
FOR J := 0 TO N - 1 DO
WriteString("----");
END;
... |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Phix | Phix | function rng(integer modifier)
while true do
atom r1 := rnd()
if rnd() < modifier(r1) then
return r1
end if
end while
end function
function modifier(atom x)
return iff(x < 0.5 ? 2 * (0.5 - x)
: 2 * (x - 0.5))
end function
constant N ... |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Python | Python | import random
from typing import List, Callable, Optional
def modifier(x: float) -> float:
"""
V-shaped, modifier(x) goes from 1 at 0 to 0 at 0.5 then back to 1 at 1.0 .
Parameters
----------
x : float
Number, 0.0 .. 1.0 .
Returns
-------
float
Target probability ... |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #11l | 11l | F modp(m, n)
V result = m % n
I result < 0
result += n
R result
F getA004290(n)
I n == 1
R BigInt(1)
V arr = [[0] * n] * n
arr[0][0] = 1
arr[0][1] = 1
V m = 0
V ten = BigInt(10)
V nBi = BigInt(n)
L
m++
I arr[m - 1][Int(modp(-pow(ten, m), nBi))] == 1
L.... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"HIMELIB"
PROC_himeinit("")
PROC_hiputdec(1, "2988348162058574136915891421498819466320163312926952423791023078876139")
PROC_hiputdec(2, "2351399303373464486466122544523690094744975233415544072992656881240319")
PROC_hiputdec(3, "10000000000000000000000000000000000000000")
... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #Bracmat | Bracmat | ( ( mod-power
= base exponent modulus result
. !arg:(?base,?exponent,?modulus)
& !exponent:~<0
& 1:?result
& whl
' ( !exponent:>0
& ( ( mod$(!exponent.2):1
& mod$(!result*!base.!modulus):?result
& -1
... |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaysty... | #D | D | import std.stdio;
version(unittest) {
void assertEquals(T)(T actual, T expected) {
import core.exception;
import std.conv;
if (actual != expected) {
throw new AssertError("Actual [" ~ to!string(actual) ~ "]; Expected [" ~ to!string(expected) ~ "]");
}
}
}
void mai... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #FOCAL | FOCAL | 01.10 F N=1,40;D 2
01.20 Q
02.10 S M=0
02.20 S M=M+1
02.30 S D=N*M
02.40 D 3
02.50 I (N-S)2.2,2.6,2.2
02.60 T "N",%2,N," M",%6,M,!
03.10 S S=0
03.20 S E=FITR(D/10)
03.30 S S=S+(D-E*10)
03.40 S D=E
03.50 I (-D)3.2 |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Forth | Forth | : digit-sum ( u -- u )
dup 10 < if exit then
10 /mod recurse + ;
: main
1+ 1 do
0
begin
1+ dup i * digit-sum i =
until
8 .r i 10 mod 0= if cr else space then
loop ;
70 main
bye |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfect... | #Haskell | Haskell | {-# LANGUAGE DeriveFunctor #-}
import Data.List
import Data.Ord
import Data.Function (on)
------------------------------------------------------------
-- memoization utilities
data Memo a = Node a (Memo a) (Memo a)
deriving Functor
memo :: Integral a => Memo p -> a -> p
memo (Node a l r) n
| n == 0 = a
| od... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Tcl | Tcl | package require Tcl 8.5
proc unsafe {y} {
global b
set x [lindex $b $y]
for {set i 1} {$i <= $y} {incr i} {
set t [lindex $b [expr {$y - $i}]]
if {$t==$x || $t==$x-$i || $t==$x+$i} {
return 1
}
}
return 0
}
proc putboard {} {
global b s N
puts "\n\nSolution #[incr s]"
for {se... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #Python | Python | import math
MAXITER = 151
def minkowski(x):
if x > 1 or x < 0:
return math.floor(x) + minkowski(x - math.floor(x))
p = int(x)
q = 1
r = p + 1
s = 1
d = 1.0
y = float(p)
while True:
d /= 2
if y + d == y:
break
m = p + r
if m ... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Tailspin | Tailspin |
templates male
when <=0> do 0 !
otherwise def n: $;
$n - 1 -> male -> female -> $n - $ !
end male
templates female
when <=0> do 1 !
otherwise def n: $;
$n - 1 -> female -> male -> $n - $ !
end female
0..10 -> 'M$;: $->male; F$;: $->female;
' -> !OUT::write
|
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Wren | Wren | import "random" for Random
var montyHall = Fn.new { |games|
var rand = Random.new()
var switchWins = 0
var stayWins = 0
for (i in 1..games) {
var doors = [0] * 3 // all zero (goats) by default
doors[rand.int(3)] = 1 // put car in a random door
var choice = rand.int(3) ... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #MOO | MOO |
@verb me:@tables none none none rxd
@program me:@tables
player:tell(" | 1 2 3 4 5 6 7 8 9 10 11 12");
player:tell("-------------------------------------------------------------------");
for i in [1..12]
line = ((i < 10) ? " " | " ") + tostr(i) + " | ";
for j in [1..12]
... |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #R | R | library(NostalgiR) #For the textual histogram.
modifier <- function(x) 2*abs(x - 0.5)
gen <- function()
{
repeat
{
random <- runif(2)
if(random[2] < modifier(random[1])) return(random[1])
}
}
data <- replicate(100000, gen())
NostalgiR::nos.hist(data, breaks = 20, pch = "#") |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #REXX | REXX | /*REXX program generates a "<" shaped probability of number generation using a modifier.*/
parse arg randn bins seed . /*obtain optional argument from the CL.*/
if randN=='' | randN=="," then randN= 100000 /*Not specified? Then use the default.*/
if bins=='' | bins=="," then bins= 20 ... |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #ALGOL_68 | ALGOL 68 | BEGIN
# returns B10 for the specified n or -1 if it cannot be found #
# based on Rick Heylen's C program linked from the OEIS site #
PROC find b10 = ( INT n )LONG INT:
IF n < 1 THEN -1
ELIF n = 1 THEN 1
ELSE
[ 0 : n ]LONG INT pow, val;
INT x, ten... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #C | C | #include <gmp.h>
int main()
{
mpz_t a, b, m, r;
mpz_init_set_str(a, "2988348162058574136915891421498819466320"
"163312926952423791023078876139", 0);
mpz_init_set_str(b, "2351399303373464486466122544523690094744"
"975233415544072992656881240319", 0);
mpz_init(m);
mpz_ui_pow_ui(m, 10, 40);
mpz_init(r)... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #C.23 | C# | using System;
using System.Numerics;
class Program
{
static void Main() {
var a = BigInteger.Parse("2988348162058574136915891421498819466320163312926952423791023078876139");
var b = BigInteger.Parse("2351399303373464486466122544523690094744975233415544072992656881240319");
var m = BigInteg... |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaysty... | #Factor | Factor | USING: accessors generalizations io kernel math math.functions
parser prettyprint prettyprint.custom sequences ;
IN: rosetta-code.modular-arithmetic
RENAME: ^ math.functions => **
! Define a modular integer class.
TUPLE: mod-int
{ n integer read-only } { mod integer read-only } ;
! Define a constructor for mod-... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Go | Go | package main
import "rcu"
func main() {
var res []int
for n := 1; n <= 70; n++ {
m := 1
for rcu.DigitSum(m*n, 10) != n {
m++
}
res = append(res, m)
}
rcu.PrintTable(res, 7, 10, true)
} |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Haskell | Haskell | import Data.Bifunctor (first)
import Data.List (elemIndex, intercalate, transpose)
import Data.List.Split (chunksOf)
import Data.Maybe (fromJust)
import Text.Printf (printf)
------------------------- A131382 ------------------------
a131382 :: [Int]
a131382 =
fromJust . (elemIndex <*> productDigitSums)
<$> [1... |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfect... | #J | J | step=: {{
~.((#~ 1<:]),y-/m),(#~ (=<.)),y%/n
}}
steps=: {{
m step n^:(1 - 1 e. ])^:a:
}}
show=: {{
paths=.,:,:0 0 1 NB. operator, operand, net value
m=.,m [ n=.,n NB. m: subtractors, n: divisors
for_ok.}.|.m steps n y do. NB. ok: valid net values
last=.{."2 paths
subs=. (1,.m,.0)+"2]0 0 ... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #UNIX_Shell | UNIX Shell | #!/bin/bash
# variable declaration
typeset -i BoardSize=8
typeset -i p=0
typeset -i total=0
typeset -i board
# initialization
function init
{
for (( i=0;i<$BoardSize;i++ ))
do
(( board[$i]=-1 ))
done
}
# check if queen can be placed
function place
{
typeset -i flag=1
for (( i=... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #Raku | Raku | # 20201120 Raku programming solution
my \MAXITER = 151;
sub minkowski(\x) {
return x.floor + minkowski( x - x.floor ) if x > 1 || x < 0 ;
my $y = my $p = x.floor;
my ($q,$s,$d) = 1 xx 3;
my $r = $p + 1;
loop {
last if ( $y + ($d /= 2) == $y ) ||
( my $m = $p + $r) < ... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Tcl | Tcl | proc m {n} {
if { $n == 0 } { expr 0; } else {
expr {$n - [f [m [expr {$n-1}] ]]};
}
}
proc f {n} {
if { $n == 0 } { expr 1; } else {
expr {$n - [m [f [expr {$n-1}] ]]};
}
}
for {set i 0} {$i < 20} {incr i} {
puts -nonewline [f $i];
puts -nonewline " ";
}
puts ""
for {set i 0} {$i < 20} {inc... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #X.2B.2B | X++ | //Evidence of the Monty Hall solution in Dynamics AX (by Wessel du Plooy - HiGH Software).
int changeWins = 0;
int noChangeWins = 0;
int attempts;
int picked;
int reveal;
int switchdoor;
int doors[];
for (attempts = 0; attempts < 32768; attempts++)
{
doors[1] = 0; ... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #XPL0 | XPL0 | def Games = 10000; \number of games simulated
int Game, Wins;
include c:\cxpl\codes;
proc Play(Switch); \Play one game
int Switch;
int Car, Player, Player0, Monty;
[Car:= Ran(3); \randomly place car behind a door
Player0:= Ran(3); \player randomly chooses a doo... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #MUMPS | MUMPS | MULTTABLE(SIZE)
;Print out a multiplication table
;SIZE is the size of the multiplication table to make
;MW is the maximum width of the numbers
;D is the down axis
;A is the across axis
;BAR is the horizontal bar under the operands
NEW MW,D,A,BAR
IF $DATA(SIZE)<1 SET SIZE=12
SET MW=$LENGTH(SIZE*SIZE)
SET BAR=... |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Raku | Raku | sub modified_random_distribution ( Code $modifier --> Seq ) {
return lazy gather loop {
my ( $r1, $r2 ) = rand, rand;
take $r1 if $modifier.($r1) > $r2;
}
}
sub modifier ( Numeric $x --> Numeric ) {
return 2 * ( $x < 1/2 ?? ( 1/2 - $x )
!! ( $x - 1/2 ) );
}
sub p... |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #AppleScript | AppleScript | on b10(n)
if (n < 1) then error
-- Each factor of n that's either 10, 2, or 5 will contribute just a zero each to the end of the B10.
-- Count and lose any such factors here to leave a potentially much smaller n (nx) to process.
-- The relevant number of zeros will be appended to the shorter result afte... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #C.2B.2B | C++ | #include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/integer.hpp>
int main() {
using boost::multiprecision::cpp_int;
using boost::multiprecision::pow;
using boost::multiprecision::powm;
cpp_int a("298834816205857413691589142149881946632016331292695242379102307... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #Clojure | Clojure | (defn powerMod "modular exponentiation" [b e m]
(defn m* [p q] (mod (* p q) m))
(loop [b b, e e, x 1]
(if (zero? e) x
(if (even? e) (recur (m* b b) (/ e 2) x)
(recur (m* b b) (quot e 2) (m* b x)))))) |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaysty... | #Forth | Forth | \ We would normally define operators that have a suffix `m' in order
\ not to be confused: +m -m *m /m **m
\ Also useful is %:m reduce a number modulo.
\ Words that may be not be present in the kernel.
\ This example loads them in ciforth.
WANT ALIAS VOCABULARY
VARIABLE _m ( Modulo number)
\ Set the modulus to m .
... |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaysty... | #Go | Go | package main
import "fmt"
// Define enough of a ring to meet the needs of the task. Addition and
// multiplication are mentioned in the task; multiplicative identity is not
// mentioned but is useful for the power function.
type ring interface {
add(ringElement, ringElement) ringElement
mul(ringElement, ... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #J | J |
findfirst=: {{
($:@((+1+i.@+:)@#)@[`(+&{. I.)@.(1 e. ]) u) ,1
}}
A131382=: {{y&{{x = sumdigits x*y}} findfirst}}"0
sumdigits=: +/@|:@(10&#.inv) |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Julia | Julia | minproddigsum(n) = findfirst(i -> sum(digits(n * i)) == n, 1:typemax(Int32))
for j in 1:70
print(lpad(minproddigsum(j), 10), j % 7 == 0 ? "\n" : "")
end
|
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfect... | #Java | Java |
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MinimalStepsDownToOne {
public static void main(String[] args) {
runTasks(getFunctions1());
runTasks(getFunctions2());
runTasks(getFunctions3());
}
private static v... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Ursala | Ursala | #import std
#import nat
remove_reflections = ^D(length@ht,~&); ~&K2hlPS+ * ^lrNCCs/~&r difference*D
remove_rotations = ~&K2hlrS2S+ * num; ~&srlXSsPNCCs
#executable <'par',''>
#optimize+
queens =
%np+~command.options.&h.keyword.&iNC; -+
~&iNC+ file$[contents: --<''>+ mat` *+ %nP*=*],
remove_rotations+ re... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #REXX | REXX | /*REXX program uses the Minkowski question─mark function to convert a continued fraction*/
numeric digits 40 /*use enough dec. digits for precision.*/
say fmt( mink( 0.5 * (1+sqrt(5) ) ) ) fmt( 5/3 )
say fmt( minkI(-5/9) ) fmt( (sqrt(13) - 7) / 6)
say fmt( mink(... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #TI-89_BASIC | TI-89 BASIC | Define F(n) = when(n=0, 1, n - M(F(n - 1)))
Define M(n) = when(n=0, 0, n - F(M(n - 1))) |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Yabasic | Yabasic |
numTiradas = 1000000
for i = 1 to numTiradas
pta_coche = int(ran(3)) + 1
pta_elegida = int(ran(3)) + 1
if pta_coche <> pta_elegida then
pta_montys = 6 - pta_coche - pta_elegida
else
repeat
pta_montys = int(ran(3)) + 1
until pta_montys <> pta_coche
end if
// manteenr elección
if pta_coche = pta_elegi... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #zkl | zkl | const games=0d100_000;
reg switcherWins=0, keeperWins=0, shown=0;
do(games){
doors := L(0,0,0);
doors[(0).random(3)] = 1; // Set which one has the car
choice := (0).random(3); // Choose a door
while(1){ shown = (0).random(3);
if (not (shown == choice or doors[shown] == 1)) break; }
switcherWins... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Neko | Neko | /**
Multiplication table, in Neko
Tectonics:
nekoc multiplication-table.neko
neko multiplication-table
*/
var sprintf = $loader.loadprim("std@sprintf", 2);
var i, j;
i = 1;
$print(" X |");
while i < 13 {
$print(sprintf("%4d", i));
i += 1;
}
$print("\n");
$print(" ---+");
i = 1;
while i < 13 {
$prin... |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
var rgen = Random.new()
var rng = Fn.new { |modifier|
while (true) {
var r1 = rgen.float()
var r2 = rgen.float()
if (r2 < modifier.call(r1)) {
return r1
}
}
}
var modifier = Fn.new { |x| (x < 0.5) ? 2 * (0.5 - x) ... |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #C | C | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
__int128 imax(__int128 a, __int128 b) {
if (a > b) {
return a;
}
return b;
}
__int128 ipow(__int128 b, __int128 n) {
__int128 res;
if (n == 0) {
return 1;
}
if (n == 1) {
return b;
... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #Common_Lisp | Common Lisp | (defun rosetta-mod-expt (base power divisor)
"Return BASE raised to the POWER, modulo DIVISOR.
This function is faster than (MOD (EXPT BASE POWER) DIVISOR), but
only works when POWER is a non-negative integer."
(setq base (mod base divisor))
;; Multiply product with base until power is zero.
(do ((product 1... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #Crystal | Crystal | require "big"
module Integer
module Powmod
# Compute self**e mod m
def powmod(e, m)
r, b = 1, self.to_big_i
while e > 0
r = (b * r) % m if e.odd?
b = (b * b) % m
e >>= 1
end
r
end
end
end
struct Int; include Integer::Powmod end
a = "29883481620585... |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaysty... | #Haskell | Haskell | -- We use a couple of GHC extensions to make the program cooler. They let us
-- use / as an operator and 13 as a literal at the type level. (The library
-- also provides the fancy Zahlen (ℤ) symbol as a synonym for Integer.)
{-# Language DataKinds #-}
{-# Language TypeOperators #-}
import Data.Modular
f :: ℤ/13... |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaysty... | #J | J | f=: (+./1 1,:_101{.1x)&p. |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #MAD | MAD | NORMAL MODE IS INTEGER
VECTOR VALUES FMT = $2HA(,I2,4H) = ,I8*$
THROUGH NUMBER, FOR N = 1, 1, N.G.70
MULT THROUGH MULT, FOR M = 1, 1, N.E.DSUM.(M*N)
NUMBER PRINT FORMAT FMT, N, M
INTERNAL FUNCTION(X)
ENTRY TO DSUM.
SUM = 0
... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Pascal | Pascal | program m_by_n_sumofdgts_m;
//Like https://oeis.org/A131382/b131382.txt
{$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$ENDIF}
uses
sysutils;
const
BASE = 10;
BASE4 = BASE*BASE*BASE*BASE;
MAXDGTSUM4 = 4*(BASE-1);
var
{$ALIGN 32}
SoD: array[0..BASE4-1] of byte;
{$ALIGN 32}
DtgBase4 :array[0..7] o... |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfect... | #Julia | Julia | import Base.print
struct Action{T}
f::Function
i::T
end
struct ActionOutcome{T}
act::Action{T}
out::T
end
Base.print(io::IO, ao::ActionOutcome) = print(io, "$(ao.act.f) $(ao.act.i) yields $(ao.out)")
memoized = Dict{Int, Int}()
function findshortest(start, goal, fails, actions, verbose=true, m... |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfect... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | $RecursionLimit = 3000;
ClearAll[MinimalStepToOne, MinimalStepToOneHelper]
MinimalStepToOne[n_Integer] := Module[{res},
res = Reap[MinimalStepToOneHelper[{n}]][[-1, 1]];
SortBy[res, Length]
]
MinimalStepToOneHelper[steps_List] := Module[{n, out},
n = Last[steps];
If[n == 1,
Sow[steps];
,
If[Divisible... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #VBA | VBA | 'N-queens problem - non recursive & structured - vba - 26/02/2017
Sub n_queens()
Const l = 15 'number of queens
Const b = False 'print option
Dim a(l), s(l), u(4 * l - 2)
Dim n, m, i, j, p, q, r, k, t, z
For i = 1 To UBound(a): a(i) = i: Next i
For n = 1 To l
m = 0
i = 1
... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #Wren | Wren | import "/fmt" for Fmt
var MAXITER = 151
var minkowski // predeclare as recursive
minkowski = Fn.new { |x|
if (x > 1 || x < 0) return x.floor + minkowski.call(x - x.floor)
var p = x.floor
var q = 1
var r = p + 1
var s = 1
var d = 1
var y = p
while (true) {
d = d / 2
if... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #TXR | TXR | (defun f (n)
(if (>= 0 n)
1
(- n (m (f (- n 1))))))
(defun m (n)
(if (>= 0 n)
0
(- n (f (m (- n 1))))))
(each ((n (range 0 15)))
(format t "f(~s) = ~s; m(~s) = ~s\n" n (f n) n (m n))) |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Nim | Nim | import strfmt
const n = 12
for j in 1..n:
stdout.write "{:3d}{:s}".fmt(j, if n-j>0: " " else: "\n")
for j in 0..n:
stdout.write if n-j>0: "----" else: "+\n"
for i in 1..n:
for j in 1..n:
stdout.write if j<i: " " else: "{:3d} ".fmt(i*j)
echo "| {:2d}".fmt(i) |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #C.23 | C# | using System;
using System.Collections.Generic;
using static System.Console;
class Program {
static string B10(int n) {
int[] pow = new int[n + 1], val = new int[29];
for (int count = 0, ten = 1, x = 1; x <= n; x++) {
val[x] = ten;
for (int j = 0, t; j <= n; j++)
if (pow[j] != 0 && pow... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #D | D | module modular_exponentiation;
private import std.bigint;
BigInt powMod(BigInt base, BigInt exponent, in BigInt modulus)
pure nothrow /*@safe*/ in {
assert(exponent >= 0);
} body {
BigInt result = 1;
while (exponent) {
if (exponent & 1)
result = (result * base) % modulus;
ex... |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaysty... | #Java | Java | public class ModularArithmetic {
private interface Ring<T> {
Ring<T> plus(Ring<T> rhs);
Ring<T> times(Ring<T> rhs);
int value();
Ring<T> one();
default Ring<T> pow(int p) {
if (p < 0) {
throw new IllegalArgumentException("p must be zero or ... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m
use warnings;
use ntheory qw( sumdigits );
my @answers = map
{
my $m = 1;
$m++ until sumdigits($m*$_) == $_;
$m;
} 1 .. 70;
print "@answers\n\n" =~ s/.{65}\K /\n/gr; |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Phix | Phix | with javascript_semantics
integer c = 0, n = 1
while c<70 do
integer m = 1
while true do
integer nm = n*m, t = 0
while nm do
t += remainder(nm,10)
nm = floor(nm/10)
end while
if t=n then exit end if
m += 1
end while
c += 1
printf(1,"%-8... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.