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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #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(‘2988348162058574136915891421498819466320163312926952423791023078876139’),
BigInt(‘2351399303373464486466122544523690094744975233415544072992656881240319’),
BigInt(10) ^ 40)) |
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
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #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 ModularArithmetic b) {
return make(a.value + b.value, a.modulus);
}
struct ModularArithmetic addi(const struct ModularArithmetic a, const int v) {
return make(a.value + v, a.modulus);
}
struct ModularArithmetic mul(const struct ModularArithmetic a, const struct ModularArithmetic b) {
return make(a.value * b.value, a.modulus);
}
struct ModularArithmetic pow(const struct ModularArithmetic b, int pow) {
struct ModularArithmetic r = make(1, b.modulus);
while (pow-- > 0) {
r = mul(r, b);
}
return r;
}
void print(const struct ModularArithmetic v) {
printf("ModularArithmetic(%d, %d)", v.value, v.modulus);
}
struct ModularArithmetic f(const struct ModularArithmetic x) {
return addi(add(pow(x, 100), x), 1);
}
int main() {
struct ModularArithmetic input = make(10, 13);
struct ModularArithmetic output = f(input);
printf("f(");
print(input);
printf(") = ");
print(output);
printf("\n");
return 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
| #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
end
yield(m)
n := n + 1
end
end a131382
start_up = proc ()
po: stream := stream$primary_output()
n: int := 0
for m: int in a131382() do
stream$putright(po, int$unparse(m), 9)
n := n + 1
if n = 70 then break end
if n // 10 = 0 then stream$putl(po, "") end
end
end start_up |
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 OCCURS 9 TIMES,
REDEFINES N-TIMES-M,
INDEXED BY D.
03 DIGITSUM PIC 999 VALUE ZERO.
01 OUTFMT.
03 FILLER PIC XX VALUE "A(".
03 N-OUT PIC Z9.
03 FILLER PIC X(4) VALUE ") = ".
03 M-OUT PIC Z(8)9.
PROCEDURE DIVISION.
BEGIN.
PERFORM CALC-A131382 VARYING N FROM 1 BY 1
UNTIL N IS GREATER THAN MAXIMUM.
STOP RUN.
CALC-A131382.
PERFORM FIND-LEAST-M VARYING M FROM 1 BY 1
UNTIL DIGITSUM IS EQUAL TO N.
SUBTRACT 1 FROM M.
MOVE N TO N-OUT.
MOVE M TO M-OUT.
DISPLAY OUTFMT.
FIND-LEAST-M.
MOVE ZERO TO DIGITSUM.
MULTIPLY N BY M GIVING N-TIMES-M.
PERFORM ADD-DIGIT VARYING D FROM 1 BY 1
UNTIL D IS GREATER THAN 9.
ADD-DIGIT.
ADD DIGITS(D) TO DIGITSUM. |
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 perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #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: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]");
PrintRange(lookup, 10);
PrintMaxMins(lookup);
lookup = CreateLookup(20_000, divisors, subtractors);
PrintMaxMins(lookup);
Console.WriteLine();
subtractors = new [] { 2 };
lookup = CreateLookup(2_000, divisors, subtractors);
Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]");
PrintRange(lookup, 10);
PrintMaxMins(lookup);
lookup = CreateLookup(20_000, divisors, subtractors);
PrintMaxMins(lookup);
}
private static void PrintRange((char op, int param, int steps)[] lookup, int limit) {
for (int goal = 1; goal <= limit; goal++) {
var x = lookup[goal];
if (x.param == 0) {
Console.WriteLine($"{goal} cannot be reached with these numbers.");
continue;
}
Console.Write($"{goal} takes {x.steps} {(x.steps == 1 ? "step" : "steps")}: ");
for (int n = goal; n > 1; ) {
Console.Write($"{n},{x.op}{x.param}=> ");
n = x.op == '/' ? n / x.param : n - x.param;
x = lookup[n];
}
Console.WriteLine("1");
}
}
private static void PrintMaxMins((char op, int param, int steps)[] lookup) {
var maxSteps = lookup.Max(x => x.steps);
var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList();
Console.WriteLine(items.Count == 1
? $"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}"
: $"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}"
);
}
private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors)
{
var lookup = new (char op, int param, int steps)[goal+1];
lookup[1] = ('/', 1, 0);
for (int n = 1; n < lookup.Length; n++) {
var ln = lookup[n];
if (ln.param == 0) continue;
for (int d = 0; d < divisors.Length; d++) {
int target = n * divisors[d];
if (target > goal) break;
if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1);
}
for (int s = 0; s < subtractors.Length; s++) {
int target = n + subtractors[s];
if (target > goal) break;
if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1);
}
}
return lookup;
}
private static string Delimit<T>(this IEnumerable<T> source) => string.Join(", ", source);
} |
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 armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #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 {
let bit0: Int = 1<<q0
let bit1: Int = 1<<q1
var d: Int = 0
cols[0] = bit0 | bit1 | (-1<<n)
diagl[0] = (bit0<<1|bit1)<<1
diagr[0] = (bit0>>1|bit1)>>1
var posib: Int = ~(cols[0] | diagl[0] | diagr[0])
while (d >= 0) {
while(posib != 0) {
let bit: Int = posib & -posib
let ncols: Int = cols[d] | bit
let ndiagl: Int = (diagl[d] | bit) << 1;
let ndiagr: Int = (diagr[d] | bit) >> 1;
let nposib: Int = ~(ncols | ndiagl | ndiagr);
posib^=bit
num += (ncols == -1 ? 1 : 0)
if (nposib != 0){
if(posib != 0) {
posibs[d] = posib
d += 1
}
cols[d] = ncols
diagl[d] = ndiagl
diagr[d] = ndiagr
posib = nposib
}
}
d -= 1
posib = d<0 ? n : posibs[d]
}
}
}
return num*2
}
if(CommandLine.arguments.count == 2) {
let board_size: Int = Int(CommandLine.arguments[1])!
print ("Number of solutions for board size \(board_size) is: \(nq(n:board_size))")
} else {
print("Usage: 8q <n>")
}
|
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 of the first zero.
Thus, ?(31/7) = 71/16 because 31/7 has the continued fraction representation [4;2,3] giving the binary expansion 4 + 0.01112.
Among its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits.
The question-mark function is continuous and monotonically increasing, so it has an inverse.
Produce a function for ?(x). Be careful: rational numbers have two possible continued fraction representations:
[a0;a1,... an−1,an] and
[a0;a1,... an−1,an−1,1]
Choose one of the above that will give a binary expansion ending with a 1.
Produce the inverse function ?-1(x)
Verify that ?(φ) = 5/3, where φ is the Greek golden ratio.
Verify that ?-1(-5/9) = (√13 - 7)/6
Verify that the two functions are inverses of each other by showing that ?-1(?(x))=x and ?(?-1(y))=y for x, y of your choice
Don't worry about precision error in the last few digits.
See also
Wikipedia entry: Minkowski's question-mark function
| #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.1213141516171819]]
InverseMinkowskiQuestionMark[MinkowskiQuestionMark[0.1213141516171819]] |
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 of the first zero.
Thus, ?(31/7) = 71/16 because 31/7 has the continued fraction representation [4;2,3] giving the binary expansion 4 + 0.01112.
Among its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits.
The question-mark function is continuous and monotonically increasing, so it has an inverse.
Produce a function for ?(x). Be careful: rational numbers have two possible continued fraction representations:
[a0;a1,... an−1,an] and
[a0;a1,... an−1,an−1,1]
Choose one of the above that will give a binary expansion ending with a 1.
Produce the inverse function ?-1(x)
Verify that ?(φ) = 5/3, where φ is the Greek golden ratio.
Verify that ?-1(-5/9) = (√13 - 7)/6
Verify that the two functions are inverses of each other by showing that ?-1(?(x))=x and ?(?-1(y))=y for x, y of your choice
Don't worry about precision error in the last few digits.
See also
Wikipedia entry: Minkowski's question-mark function
| #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 or p < 0: break
let n = q + s
if n < 0: break
if x < m.float / n.float:
r = m
s = n
else:
y += d
p = m
q = n
result = y + d
func minkowskiInv(x: float): float =
if x notin 0.0..1.0:
return floor(x) + minkowskiInv(x - floor(x))
if x == 1 or x == 0:
return x
var
contFrac: seq[uint32]
curr = 0u32
count = 1u32
i = 0
x = x
while true:
x *= 2
if curr == 0:
if x < 1:
inc count
else:
inc i
contFrac.setLen(i + 1)
contFrac[i - 1] = count
count = 1
curr = 1
x -= 1
else:
if x > 1:
inc count
x -= 1
else:
inc i
contFrac.setLen(i + 1)
contFrac[i - 1] = count
count = 1
curr = 0
if x == floor(x):
contFrac[i] = count
break
if i == MaxIter:
break
var ret = 1 / contFrac[i].float
for j in countdown(i - 1, 0):
ret = contFrac[j].float + 1 / ret
result = 1 / ret
echo &"{minkowski(0.5*(1+sqrt(5.0))):19.16f}, {5/3:19.16f}"
echo &"{minkowskiInv(-5/9):19.16f}, {(sqrt(13.0)-7)/6:19.16f}"
echo &"{minkowski(minkowskiInv(0.718281828)):19.16f}, " &
&"{minkowskiInv(minkowski(0.1213141516171819)):19.16f}" |
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
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #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 host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #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, -- original choice
@car int , -- room with car
@alternative int -- alternative room
select @rooms = 3, @N = 100000 , @i = 0
-- EXPERIMENTS LOOP
while @i < @N begin
select @car = FLOOR(rand()*@rooms)+1 , @origin = FLOOR(rand()*@rooms)+1
select @alternative = FLOOR(rand()*(@rooms-1))+1
select @alternative = case when @alternative < @origin then @alternative else @alternative + 1 end
select @alternative = case when @origin = @car then @alternative else @car end
insert MONTY_HALL
select @i,@car,@alternative,@origin,@origin,@alternative,case when rand() < 5e-1 then @origin else @alternative end
select @i = @i + 1
end
-- RESULTS
select avg (case when [KEEP] = CAR then 1e0 else 0e0 end )*1e2 as [% OF WINS FOR KEEP],
avg (case when [CHANGE] = CAR then 1e0 else 0e0 end )*1e2 as [% OF WINS FOR CHANGE],
avg (case when [RANDOM] = CAR then 1e0 else 0e0 end )*1e2 as [% OF WINS FOR RANDOM]
from MONTY_HALL
---- END ------------
|
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.WriteLine("+")
For i = 1 To n
For j = 1 To n
If j < i Then
TextWindow.Write(" ")
Else
TextWindow.CursorLeft = (j - 1) * 4 + (3 - Text.GetLength(i * j))
TextWindow.Write(i * j)
TextWindow.Write(" ")
EndIf
EndFor
TextWindow.Write("| ")
TextWindow.CursorLeft = n * 4 + (4 - Text.GetLength(i))
TextWindow.Write(i)
TextWindow.WriteLine("")
EndFor
|
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 random numbers to the probability given by function modifier:
while True:
random1 = rgen()
random2 = rgen()
if random2 < modifier(random1):
answer = random1
break
endif
endwhile
Task
Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:
modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5)
Create a generator of random numbers with probabilities modified by the above function.
Generate >= 10,000 random numbers subject to the probability modification.
Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.
Show your output here, on this page.
| #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 random numbers to the probability given by function modifier:
while True:
random1 = rgen()
random2 = rgen()
if random2 < modifier(random1):
answer = random1
break
endif
endwhile
Task
Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:
modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5)
Create a generator of random numbers with probabilities modified by the above function.
Generate >= 10,000 random numbers subject to the probability modification.
Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.
Show your output here, on this page.
| #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[], 100000];
{bins, counts} = HistogramList[numbers, {0, 1, 0.05}, "PDF"];
Grid[MapThread[{#1, " - ", StringJoin@ConstantArray["X", Round[20 #2]]} &, {Partition[bins, 2, 1], counts}], Alignment -> Left] |
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 random numbers to the probability given by function modifier:
while True:
random1 = rgen()
random2 = rgen()
if random2 < modifier(random1):
answer = random1
break
endif
endwhile
Task
Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:
modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5)
Create a generator of random numbers with probabilities modified by the above function.
Generate >= 10,000 random numbers subject to the probability modification.
Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.
Show your output here, on this page.
| #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
const
N = 100_000
NumBins = 20
HistChar = "■"
HistCharSize = 125
BinSize = 1 / NumBins
randomize()
var bins: array[NumBins, int]
for i in 0..<N:
let rn = rand(modifier)
let bn = int(rn / BinSize)
inc bins[bn]
echo &"Modified random distribution with {N} samples in range [0, 1):"
echo " Range Number of samples within that range"
for i in 0..<NumBins:
let hist = repeat(HistChar, (bins[i] / HistCharSize).toInt)
echo &"{BinSize * float(i):4.2f} ..< {BinSize * float(i + 1):4.2f} {hist} {bins[i]}" |
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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #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(Positive'Max(A'Length, B'Length), 40);
-- the number of decimals to store A, B, and result
Bits: constant Positive := (34*D)/10;
-- (slightly more than) the number of bits to store A, B, and result
package LN is new Crypto.Types.Big_Numbers (Bits + (32 - Bits mod 32));
-- the actual number of bits has to be a multiple of 32
use type LN.Big_Unsigned;
function "+"(S: String) return LN.Big_Unsigned
renames LN.Utils.To_Big_Unsigned;
M: LN.Big_Unsigned := (+"10") ** (+"40");
begin
Ada.Text_IO.Put("A**B (mod 10**40) = ");
Ada.Text_IO.Put_Line(LN.Utils.To_String(LN.Mod_Utils.Pow((+A), (+B), M)));
end Mod_Exp; |
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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #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
(ODD e | result := (result * b) MOD modulus);
e OVERAB 2; b := (b * b) MOD modulus
OD
FI;
result
END;
LLI a = 2988348162058574136915891421498819466320163312926952423791023078876139;
LLI b = 2351399303373464486466122544523690094744975233415544072992656881240319;
LLI m = 10000000000000000000000000000000000000000;
printf (($"Last 40 digits = ", 40dl$, mod power (a, b, m)))
END
|
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
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #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>, IMultiplication<ModInt>, IPower<ModInt>, IOne<ModInt> {
private int modulo;
public ModInt(int value, int modulo) {
Value = value;
this.modulo = modulo;
}
public int Value { get; }
public ModInt One() {
return new ModInt(1, modulo);
}
public ModInt Add(ModInt rhs) {
return this + rhs;
}
public ModInt Multiply(ModInt rhs) {
return this * rhs;
}
public ModInt Power(int pow) {
return Pow(this, pow);
}
public override string ToString() {
return string.Format("ModInt({0}, {1})", Value, modulo);
}
public static ModInt operator +(ModInt lhs, ModInt rhs) {
if (lhs.modulo != rhs.modulo) {
throw new ArgumentException("Cannot add rings with different modulus");
}
return new ModInt((lhs.Value + rhs.Value) % lhs.modulo, lhs.modulo);
}
public static ModInt operator *(ModInt lhs, ModInt rhs) {
if (lhs.modulo != rhs.modulo) {
throw new ArgumentException("Cannot add rings with different modulus");
}
return new ModInt((lhs.Value * rhs.Value) % lhs.modulo, lhs.modulo);
}
public static ModInt Pow(ModInt self, int p) {
if (p < 0) {
throw new ArgumentException("p must be zero or greater");
}
int pp = p;
ModInt pwr = self.One();
while (pp-- > 0) {
pwr *= self;
}
return pwr;
}
}
class Program {
static T F<T>(T x) where T : IAddition<T>, IMultiplication<T>, IPower<T>, IOne<T> {
return x.Power(100).Add(x).Add(x.One());
}
static void Main(string[] args) {
ModInt x = new ModInt(10, 13);
ModInt y = F(x);
Console.WriteLine("x ^ 100 + x + 1 for x = {0} is {1}", x, y);
}
}
} |
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;
end sub;
var n: uint8 := 1;
while n <= 70 loop
print_i32(a131382(n));
if n % 10 == 0 then print_nl();
else print_char(' ');
end if;
n := n + 1;
end loop; |
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 digitsum(ulong n) byte:
byte sum;
sum := 0;
while n /= 0 do
sum := sum + make(n % 10, byte);
n := n / 10
od;
sum
corp
proc nonrec a131382(ulong n) ulong:
ulong m;
m := 1;
while digitsum(m * n) /= n do
m := m + 1
od;
m
corp
proc nonrec main() void:
byte n;
for n from 1 upto MAX do
write(a131382(n):9);
if (n & 7) = 0 then writeln() fi
od
corp |
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 perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #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 Then
For i As Integer = 0 To Paso-1
MinOps(i) = Ops(i)
MinNs(i) = Ns(i)
Next i
minPasos = Paso
End If
End If
If Paso >= minPasos Then Exit Sub 'don't search further
If N Mod 3 = 0 Then Ops(Paso) = 3 : Ns(Paso) = N/3 : Reduce(N/3, Paso+1)
If N Mod 2 = 0 Then Ops(Paso) = 2 : Ns(Paso) = N/2 : Reduce(N/2, Paso+1)
Ops(Paso) = -Subtractor
Ns(Paso) = N-Subtractor
Reduce(N-Subtractor, Paso+1)
End Sub
Sub ShowSteps(N As Integer) 'Show minimal steps and how N steps to 1
minPasos = 50000
Reduce(N, 0)
Print "N = " & N & " takes " & minPasos & " steps: N";
For i As Integer = 0 To minPasos-1
Print Iif(Sgn(MinOps(i)) < 0, " -", " /");
Print Abs(MinOps(i)) & "=>" & MinNs(i); '" "
Next i
Print
End Sub
Sub ShowCount(Range As Integer) 'Show count of maximum minimal steps and their Ns
Dim As Integer N, MaxSteps
MaxSteps = 0 'find maximum number of minimum steps
For N = 1 To Range
minPasos = 50000
Reduce(N, 0)
If minPasos > MaxSteps Then MaxSteps = minPasos
Next N
Print "Maximum steps:"; MaxSteps; " for N =";
For N = 1 To Range 'show numbers (Ns) for Maximum steps
minPasos = 50000
Reduce(N, 0)
If minPasos = MaxSteps Then Print N; '" ";
Next N
Print
End Sub
Dim As Integer N
Subtractor = 1 '1.
For N = 1 To 10
ShowSteps(N)
Next N
ShowCount(2000) '2.
ShowCount(20000) '2a.
Print
Subtractor = 2 '3.
For N = 1 To 10
ShowSteps(N)
Next N
ShowCount(2000) '4.
ShowCount(20000) '4a.
Sleep |
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 armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #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 diagonal_moves {
foreach (row[i]) foreach (row[j]) if (i < j) {
`ABS_DIFF(row[i], row[j]) != `ABS_DIFF(i,j);
}
}
function void next;
randomize;
foreach (row[i]) begin
automatic bit [SIZE-1:0] x = 1 << row[i];
$display( " %b", x );
end
$display("--");
endfunction
endclass
board b = new;
initial repeat(1) b.next;
endprogram
|
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 of the first zero.
Thus, ?(31/7) = 71/16 because 31/7 has the continued fraction representation [4;2,3] giving the binary expansion 4 + 0.01112.
Among its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits.
The question-mark function is continuous and monotonically increasing, so it has an inverse.
Produce a function for ?(x). Be careful: rational numbers have two possible continued fraction representations:
[a0;a1,... an−1,an] and
[a0;a1,... an−1,an−1,1]
Choose one of the above that will give a binary expansion ending with a 1.
Produce the inverse function ?-1(x)
Verify that ?(φ) = 5/3, where φ is the Greek golden ratio.
Verify that ?-1(-5/9) = (√13 - 7)/6
Verify that the two functions are inverses of each other by showing that ?-1(?(x))=x and ?(?-1(y))=y for x, y of your choice
Don't worry about precision error in the last few digits.
See also
Wikipedia entry: Minkowski's question-mark function
| #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 + ($d /= 2) == $y ) or
( my $m = $p + $r) < 0 or
( my $n = $q + $s) < 0;
$x < $m/$n ? ($r,$s) = ($m, $n) : ($y += $d and ($p,$q) = ($m, $n) );
}
return $y + $d
}
sub minkowskiInv {
my($x) = @_;
return floor($x) + minkowskiInv($x - floor($x)) if $x > 1 || $x < 0;
return $x if $x == 1 || $x == 0 ;
my @contFrac = 0;
my $i = my $curr = 0 ; my $count = 1;
while () {
$x *= 2;
if ($curr == 0) {
if ($x < 1) {
$count++
} else {
$i++;
push @contFrac, 0;
$contFrac[$i-1] = $count;
($count,$curr) = (1,1);
$x--;
}
} else {
if ($x > 1) {
$count++;
$x--;
} else {
$i++;
push @contFrac, 0;
@contFrac[$i-1] = $count;
($count,$curr) = (1,0);
}
}
if ($x == floor($x)) { @contFrac[$i] = $count; last }
last if $i == $MAXITER;
}
my $ret = 1 / $contFrac[$i];
for (my $j = $i - 1; $j >= 0; $j--) { $ret = $contFrac[$j] + 1/$ret }
return 1 / $ret
}
printf "%19.16f %19.16f\n", minkowski(0.5*(1 + sqrt(5))), 5/3;
printf "%19.16f %19.16f\n", minkowskiInv(-5/9), (sqrt(13)-7)/6;
printf "%19.16f %19.16f\n", minkowski(minkowskiInv(0.718281828)), minkowskiInv(minkowski(0.1213141516171819)); |
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
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #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 host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #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 number of doors
[ "$1" = "" ] || num_rounds=$[$1+0]
[ "$2" = "" ] || num_doors=$[$2+0]
nbase=1 # or 0 if we want to see door numbers zero-based
num_win=0; num_lose=0
echo "Playing $num_rounds times, with $num_doors doors."
[ "$num_doors" -lt 3 ] && {
echo "Hey, there has to be at least 3 doors!!"
exit 1
}
echo
function one_round() {
winning_door=$[$RANDOM % $num_doors ]
player_picks_door=$[$RANDOM % $num_doors ]
# Host leaves this door AND the player's first choice closed, opens all others
# (this WILL loop forever if there is only 1 door)
host_skips_door=$winning_door
while [ "$host_skips_door" = "$player_picks_door" ]; do
#echo -n "(Host looks at door $host_skips_door...) "
host_skips_door=$[$RANDOM % $num_doors]
done
# Output the result of this round
#echo "Round $[$nbase+current_round]: "
echo -n "Player chooses #$[$nbase+$player_picks_door]. "
[ "$num_doors" -ge 10 ] &&
# listing too many door numbers (10 or more) will just clutter the output
echo -n "Host opens all except #$[$nbase+$host_skips_door] and #$[$nbase+$player_picks_door]. " \
|| {
# less than 10 doors, we list them one by one instead of "all except ?? and ??"
echo -n "Host opens"
host_opens=0
while [ "$host_opens" -lt "$num_doors" ]; do
[ "$host_opens" != "$host_skips_door" ] && [ "$host_opens" != "$player_picks_door" ] && \
echo -n " #$[$nbase+$host_opens]"
host_opens=$[$host_opens+1]
done
echo -n " "
}
echo -n "(prize is behind #$[$nbase+$winning_door]) "
echo -n "Switch from $[$nbase+$player_picks_door] to $[$nbase+$host_skips_door]: "
[ "$winning_door" = "$host_skips_door" ] && {
echo "WIN."
num_win=$[num_win+1]
} || {
echo "LOSE."
num_lose=$[num_lose+1]
}
} # end of function one_round
# ok, let's go
current_round=0
while [ "$num_rounds" -gt "$current_round" ]; do
one_round
current_round=$[$current_round+1]
done
echo
echo "Wins (switch to remaining door): $num_win"
echo "Losses (first guess was correct): $num_lose"
exit 0 |
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 random numbers to the probability given by function modifier:
while True:
random1 = rgen()
random2 = rgen()
if random2 < modifier(random1):
answer = random1
break
endif
endwhile
Task
Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:
modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5)
Create a generator of random numbers with probabilities modified by the above function.
Generate >= 10,000 random numbers subject to the probability modification.
Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.
Show your output here, on this page.
| #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};
wantarray ? @values : \@values;
}
sub modifier_notch {
my($x) = @_;
return 2 * ( $x < 1/2 ? ( 1/2 - $x )
: ( $x - 1/2 ) );
}
sub print_histogram {
our %param = (n_bins => 10, width => 80, @_);
my %counts;
$counts{ int($_ * $param{n_bins}) / $param{n_bins} }++ for @{$param{data}};
our $max_value = max values %counts;
print "Bin Counts Histogram\n";
printf "%4.2f %6d: %s\n", $_, $counts{$_}, hist($counts{$_}) for sort keys %counts;
sub hist { scalar ('■') x ( $param{width} * $_[0] / $max_value ) }
}
print_histogram( data => \@{ distribution() } );
print "\n\n";
my @samples = distribution( function => \&modifier_notch, sample_size => 50_000);
print_histogram( data => \@samples, n_bins => 20, width => 64); |
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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #AutoHotkey | AutoHotkey | #NoEnv
#SingleInstance, Force
SetBatchLines, -1
#Include mpl.ahk
MP_SET(base, "2988348162058574136915891421498819466320163312926952423791023078876139")
, MP_SET(exponent, "2351399303373464486466122544523690094744975233415544072992656881240319")
, MP_SET(modulus, "10000000000000000000000000000000000000000")
, NumGet(exponent,0,"Int") = -1 ? return : ""
, MP_SET(result, "1")
, MP_SET(TWO, "2")
while !MP_IS0(exponent)
MP_DIV(q, r, exponent, TWO)
, (MP_DEC(r) = 1
? (MP_MUL(temp, result, base)
, MP_DIV(q, result, temp, modulus))
: "")
, MP_DIV(q, r, exponent, TWO)
, MP_CPY(exponent, q)
, MP_CPY(base1, base)
, MP_MUL(base2, base1, base)
, MP_DIV(q, base, base2, modulus)
msgbox % MP_DEC(result)
Return |
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
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #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("Left-hand modulus does not match right-hand modulus.");
}
}
public:
ModularInteger(int v, int m) {
modulus = m;
value = v % m;
}
int getValue() const {
return value;
}
int getModulus() const {
return modulus;
}
ModularInteger operator+(const ModularInteger& rhs) const {
validateOp(rhs);
return ModularInteger(value + rhs.value, modulus);
}
ModularInteger operator+(int rhs) const {
return ModularInteger(value + rhs, modulus);
}
ModularInteger operator*(const ModularInteger& rhs) const {
validateOp(rhs);
return ModularInteger(value * rhs.value, modulus);
}
friend std::ostream& operator<<(std::ostream&, const ModularInteger&);
};
std::ostream& operator<<(std::ostream& os, const ModularInteger& self) {
return os << "ModularInteger(" << self.value << ", " << self.modulus << ")";
}
ModularInteger pow(const ModularInteger& lhs, int pow) {
if (pow < 0) {
throw std::runtime_error("Power must not be negative.");
}
ModularInteger base(1, lhs.getModulus());
while (pow-- > 0) {
base = base * lhs;
}
return base;
}
int main() {
using namespace std;
ModularInteger input(10, 13);
auto output = f(input);
cout << "f(" << input << ") = " << output << endl;
return 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
| #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>g -> fN (i+1L)
|n -> fN (i+(int64(ceil(float(g-n)/float n))))
fN ((((pown 10L (g/9))-1L)+int64(g%9)*(pown 10L (g/9)))/int64 g)
Seq.initInfinite((+)1>>A131382)|>Seq.take 70|>Seq.chunkBySize 10|>Seq.iter(fun n->n|>Seq.iter(printf "%13d "); printfn "")
|
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 perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #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
var op byte
for _, div := range divs {
if n%div == 0 {
d := n / div
steps := len(mins[d]) + 1
if steps < min {
min = steps
p, q, op = d, div, '/'
}
}
}
for _, sub := range subs {
if d := n - sub; d >= 1 {
steps := len(mins[d]) + 1
if steps < min {
min = steps
p, q, op = d, sub, '-'
}
}
}
mins[n] = append(mins[n], fmt.Sprintf("%c%d -> %d", op, q, p))
mins[n] = append(mins[n], mins[p]...)
}
func main() {
for r := 0; r < 2; r++ {
divs = []int{2, 3}
if r == 0 {
subs = []int{1}
} else {
subs = []int{2}
}
mins = make([][]string, limit+1)
fmt.Printf("With: Divisors: %v, Subtractors: %v =>\n", divs, subs)
fmt.Println(" Minimum number of steps to diminish the following numbers down to 1 is:")
for i := 1; i <= limit; i++ {
minsteps(i)
if i <= 10 {
steps := len(mins[i])
plural := "s"
if steps == 1 {
plural = " "
}
fmt.Printf(" %2d: %d step%s: %s\n", i, steps, plural, strings.Join(mins[i], ", "))
}
}
for _, lim := range []int{2000, 20000, 50000} {
max := 0
for _, min := range mins[0 : lim+1] {
m := len(min)
if m > max {
max = m
}
}
var maxs []int
for i, min := range mins[0 : lim+1] {
if len(min) == max {
maxs = append(maxs, i)
}
}
nums := len(maxs)
verb, verb2, plural := "are", "have", "s"
if nums == 1 {
verb, verb2, plural = "is", "has", ""
}
fmt.Printf(" There %s %d number%s in the range 1-%d ", verb, nums, plural, lim)
fmt.Printf("that %s maximum 'minimal steps' of %d:\n", verb2, max)
fmt.Println(" ", maxs)
}
fmt.Println()
}
} |
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 armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #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 $ !\)
-> \(when <?($ -> \[i]($ - $i !\) <~[<=$minor>]>)> do $ !\)
-> \(when <?($ -> \[i]($ + $i !\) <~[<=$major>]>)> do $ !\)
-> [ $..., $row] !
end addIfPossible
1..$n -> addIfPossible !
end addColumn
1..$n -> [$] -> #
when <[]($n)> do $ !
otherwise $ -> addColumn -> #
end queens
def solutions: [ 8 -> queens ];
'For 8 queens there are $solutions::length; solutions
' -> !OUT::write
def columns: ['abcdefgh'...];
'One of them is $solutions(1) -> \[i]('$columns($i);$;' !\);
' -> !OUT::write
'For 3 queens there are $:[3 -> queens] -> $::length; solutions
' -> !OUT::write
|
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 of the first zero.
Thus, ?(31/7) = 71/16 because 31/7 has the continued fraction representation [4;2,3] giving the binary expansion 4 + 0.01112.
Among its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits.
The question-mark function is continuous and monotonically increasing, so it has an inverse.
Produce a function for ?(x). Be careful: rational numbers have two possible continued fraction representations:
[a0;a1,... an−1,an] and
[a0;a1,... an−1,an−1,1]
Choose one of the above that will give a binary expansion ending with a 1.
Produce the inverse function ?-1(x)
Verify that ?(φ) = 5/3, where φ is the Greek golden ratio.
Verify that ?-1(-5/9) = (√13 - 7)/6
Verify that the two functions are inverses of each other by showing that ?-1(?(x))=x and ?(?-1(y))=y for x, y of your choice
Don't worry about precision error in the last few digits.
See also
Wikipedia entry: Minkowski's question-mark function
| #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 < 0 then exit end if
n = q + s
if n < 0 then exit end if
if x < m/n then
r = m
s = n
else
y = y + d
p = m
q = n
end if
end while
return y + d
end function
function minkowski_inv(atom x)
if x>1 or x<0 then return floor(x)+minkowski_inv(x-floor(x)) end if
if x=1 or x=0 then return x end if
sequence contfrac = {}
integer curr = 0, count = 1
while true do
x *= 2
if curr = 0 then
if x<1 then
count += 1
else
contfrac &= count
count = 1
curr = 1
x -= 1
end if
else
if x>1 then
count += 1
x -= 1
else
contfrac &= count
count = 1
curr = 0
end if
end if
if x = floor(x) then
contfrac &= count
exit
end if
if length(contfrac)=MAXITER then exit end if
end while
atom ret = 1/contfrac[$]
for i = length(contfrac)-1 to 1 by -1 do
ret = contfrac[i] + 1.0/ret
end for
return 1/ret
end function
printf(1,"%20.16f %20.16f\n",{minkowski(0.5*(1+sqrt(5))), 5/3})
printf(1,"%20.16f %20.16f\n",{minkowski_inv(-5/9), (sqrt(13)-7)/6})
printf(1,"%20.16f %20.16f\n",{minkowski(minkowski_inv(0.718281828)),
minkowski_inv(minkowski(0.1213141516171819))})
|
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
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #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
save Mr
call F Mr
result Fr
restore Mr
restore Mn
(Mn-Fr) R
endif
return R
start
i
if i <= 19
call F i
result res
" $s res ' '" $s
+ i
goif
endif
$s []
$s
i
if i <= 19
call M i
result res
" $s res ' '" $s
+ i
goif
endif
$s []
|
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 host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #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.+ div+ float~~)\rounds
#show+
main = ~&plrTS/<'stay: ','switch: '> format* <staying_wins,switching_wins> |
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 host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #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
Call("RANDOM")
#4 = Return_Value // #4 = players choice
do {
Call("RANDOM")
#5 = Return_Value // #5 = door to open
} while (#5 == #3 || #5 == #4)
if (#3 == #4) { // original choice was correct
#1++
}
if (#3 == 3 - #4 - #5) { // switched choice was correct
#2++
}
}
Ins_Text("Staying wins: ") Num_Ins(#1)
Ins_Text("Switching wins: ") Num_Ins(#2)
return
//--------------------------------------------------------------
// Generate random numbers in range 0 <= Return_Value < #91
// #90 = Seed (0 to 0x7fffffff)
// #91 = Scaling (0 to 0xffff)
:RANDOM:
#92 = 0x7fffffff / 48271
#93 = 0x7fffffff % 48271
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
return ((#90 & 0xffff) * #91 / 0x10000) |
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;
WriteString("+");
WriteLn;
FOR I := 1 TO N DO
FOR J := 1 TO N DO
IF J < I THEN
WriteString(" ");
ELSE
WriteInt(I * J, 3);
WriteString(" ");
END;
END;
WriteString("| ");
WriteInt(I, 2);
WriteLn;
END;
END MultiplicationTables.
|
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 random numbers to the probability given by function modifier:
while True:
random1 = rgen()
random2 = rgen()
if random2 < modifier(random1):
answer = random1
break
endif
endwhile
Task
Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:
modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5)
Create a generator of random numbers with probabilities modified by the above function.
Generate >= 10,000 random numbers subject to the probability modification.
Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.
Show your output here, on this page.
| #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 = 100000,
NUM_BINS = 20,
HIST_CHAR_SIZE = 125,
BIN_SIZE = 1/NUM_BINS,
LO = sq_mul(tagset(NUM_BINS-1,0),BIN_SIZE),
HI = sq_mul(tagset(NUM_BINS),BIN_SIZE),
LBLS = apply(true,sprintf,{{"[%4.2f,%4.2f)"},columnize({LO,HI})})
sequence bins := repeat(0, NUM_BINS)
for i=1 to N do
bins[floor(rng(modifier) / BIN_SIZE)+1] += 1
end for
printf(1,"Modified random distribution with %,d samples in range [0, 1):\n\n",N)
for i=1 to NUM_BINS do
sequence hist := repeat('#', round(bins[i]/HIST_CHAR_SIZE))
printf(1,"%s %s %,d\n", {LBLS[i], hist, bins[i]})
end for |
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 random numbers to the probability given by function modifier:
while True:
random1 = rgen()
random2 = rgen()
if random2 < modifier(random1):
answer = random1
break
endif
endwhile
Task
Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:
modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5)
Create a generator of random numbers with probabilities modified by the above function.
Generate >= 10,000 random numbers subject to the probability modification.
Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.
Show your output here, on this page.
| #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 for generating x; between 0 and 1.
"""
return 2*(.5 - x) if x < 0.5 else 2*(x - .5)
def modified_random_distribution(modifier: Callable[[float], float],
n: int) -> List[float]:
"""
Generate n random numbers between 0 and 1 subject to modifier.
Parameters
----------
modifier : Callable[[float], float]
Target random number gen. 0 <= modifier(x) < 1.0 for 0 <= x < 1.0 .
n : int
number of random numbers generated.
Returns
-------
List[float]
n random numbers generated with given probability.
"""
d: List[float] = []
while len(d) < n:
r1 = prob = random.random()
if random.random() < modifier(prob):
d.append(r1)
return d
if __name__ == '__main__':
from collections import Counter
data = modified_random_distribution(modifier, 50_000)
bins = 15
counts = Counter(d // (1 / bins) for d in data)
#
mx = max(counts.values())
print(" BIN, COUNTS, DELTA: HISTOGRAM\n")
last: Optional[float] = None
for b, count in sorted(counts.items()):
delta = 'N/A' if last is None else str(count - last)
print(f" {b / bins:5.2f}, {count:4}, {delta:>4}: "
f"{'#' * int(40 * count / mx)}")
last = count |
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 positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #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.break
arr[m][0] = 1
L(k) 1 .< n
arr[m][k] = max(arr[m - 1][k], arr[m - 1][Int(modp(BigInt(k) - pow(ten, m), nBi))])
V r = pow(ten, m)
V k = Int(modp(-r, nBi))
L(j) (m - 1 .< 0).step(-1)
I arr[j - 1][k] == 0
r += pow(ten, j)
k = Int(modp(BigInt(k) - pow(ten, j), nBi))
I k == 1
r++
R r
L(n) Array(1..10) [+] Array(95..105) [+] [297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878]
V result = getA004290(n)
print(‘A004290(’n‘) = ’result‘ = ’n‘ * ’(result I/ n)) |
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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"HIMELIB"
PROC_himeinit("")
PROC_hiputdec(1, "2988348162058574136915891421498819466320163312926952423791023078876139")
PROC_hiputdec(2, "2351399303373464486466122544523690094744975233415544072992656881240319")
PROC_hiputdec(3, "10000000000000000000000000000000000000000")
h1% = 1 : h2% = 2 : h3% = 3 : h4% = 4
SYS `hi_PowMod`, ^h1%, ^h2%, ^h3%, ^h4%
PRINT FN_higetdec(4) |
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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #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
| 0
)
+ !exponent
)
* 1/2
: ?exponent
& mod$(!base^2.!modulus):?base
)
& !result
)
& ( a
= 2988348162058574136915891421498819466320163312926952423791023078876139
)
& ( b
= 2351399303373464486466122544523690094744975233415544072992656881240319
)
& out$("last 40 digits = " mod-power$(!a,!b,10^40))
) |
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
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #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 main() {
auto input = ModularInteger(10,13);
auto output = f(input);
writeln("f(", input, ") = ", output);
}
V f(V)(const V x) {
return x^^100 + x + 1;
}
/// Integer tests on f
unittest {
assertEquals(f(1), 3);
assertEquals(f(0), 1);
}
/// Floating tests on f
unittest {
assertEquals(f(1.0), 3.0);
assertEquals(f(0.0), 1.0);
}
struct ModularInteger {
private:
int value;
int modulus;
public:
this(int value, int modulus) {
this.modulus = modulus;
this.value = value % modulus;
}
ModularInteger opBinary(string op : "+")(ModularInteger rhs) const in {
assert(this.modulus == rhs.modulus);
} body {
return ModularInteger((this.value + rhs.value) % this.modulus, this.modulus);
}
ModularInteger opBinary(string op : "+")(int rhs) const {
return ModularInteger((this.value + rhs) % this.modulus, this.modulus);
}
ModularInteger opBinary(string op : "*")(ModularInteger rhs) const in {
assert(this.modulus == rhs.modulus);
assert(this.value < this.modulus);
assert(rhs.value < this.modulus);
} body {
return ModularInteger((this.value * rhs.value) % this.modulus, this.modulus);
}
ModularInteger opBinary(string op : "^^")(int pow) const in {
assert(pow >= 0);
} body {
auto base = ModularInteger(1, this.modulus);
while (pow-- > 0) {
base = base * this;
}
return base;
}
string toString() {
import std.format;
return format("ModularInteger(%s, %s)", value, modulus);
}
}
/// Addition with same type of int
unittest {
auto a = ModularInteger(2,5);
auto b = ModularInteger(3,5);
assertEquals(a+b, ModularInteger(0,5));
}
/// Addition with differnt int types
unittest {
auto a = ModularInteger(2,5);
assertEquals(a+0, a);
assertEquals(a+1, ModularInteger(3,5));
}
/// Muliplication
unittest {
auto a = ModularInteger(2,5);
auto b = ModularInteger(3,5);
assertEquals(a*b, ModularInteger(1,5));
}
/// Power
unittest {
const a = ModularInteger(3,13);
assertEquals(a^^2, ModularInteger(9,13));
assertEquals(a^^3, ModularInteger(1,13));
const b = ModularInteger(10,13);
assertEquals(b^^1, ModularInteger(10,13));
assertEquals(b^^2, ModularInteger(9,13));
assertEquals(b^^3, ModularInteger(12,13));
assertEquals(b^^4, ModularInteger(3,13));
assertEquals(b^^5, ModularInteger(4,13));
assertEquals(b^^6, ModularInteger(1,13));
assertEquals(b^^7, ModularInteger(10,13));
assertEquals(b^^8, ModularInteger(9,13));
assertEquals(b^^10, ModularInteger(3,13));
assertEquals(b^^20, ModularInteger(9,13));
assertEquals(b^^30, ModularInteger(1,13));
assertEquals(b^^50, ModularInteger(9,13));
assertEquals(b^^75, ModularInteger(12,13));
assertEquals(b^^90, ModularInteger(1,13));
assertEquals(b^^95, ModularInteger(4,13));
assertEquals(b^^97, ModularInteger(10,13));
assertEquals(b^^98, ModularInteger(9,13));
assertEquals(b^^99, ModularInteger(12,13));
assertEquals(b^^100, ModularInteger(3,13));
} |
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 perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #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
| odd n = memo l (n `div` 2)
| otherwise = memo r (n `div` 2 - 1)
nats :: Integral a => Memo a
nats = Node 0 ((+1).(*2) <$> nats) ((*2).(+1) <$> nats)
memoize :: Integral a => (a -> b) -> (a -> b)
memoize f = memo (f <$> nats)
------------------------------------------------------------
data Step = Div Int | Sub Int
deriving Show
run :: Int -> Step -> [(Step, Int)]
run n s = case s of
Sub i | n > i -> [(s, n - i)]
Div d | n `mod` d == 0 -> [(s, n `div` d)]
_ -> []
minSteps :: [Step] -> Int -> (Int, [Step])
minSteps steps = go
where
go = memoize goM
goM 1 = (0, [])
goM n = minimumBy (comparing fst) $ do
(s, k) <- steps >>= run n
let (m, ss) = go k
return (m+1, s:ss) |
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 armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #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 {set y 0} {$y < $N} {incr y} {
for {set x 0} {$x < $N} {incr x} {
puts -nonewline [expr {[lindex $b $y] == $x ? "|Q" : "|_"}]
}
puts "|"
}
}
proc main {n} {
global b N
set N $n
set b [lrepeat $N 0]
set y 0
lset b 0 -1
while {$y >= 0} {
lset b $y [expr {[lindex $b $y] + 1}]
while {[lindex $b $y] < $N && [unsafe $y]} {
lset b $y [expr {[lindex $b $y] + 1}]
}
if {[lindex $b $y] >= $N} {
incr y -1
} elseif {$y < $N-1} {
lset b [incr y] -1;
} else {
putboard
}
}
}
main [expr {$argc ? int(0+[lindex $argv 0]) : 8}] |
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 of the first zero.
Thus, ?(31/7) = 71/16 because 31/7 has the continued fraction representation [4;2,3] giving the binary expansion 4 + 0.01112.
Among its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits.
The question-mark function is continuous and monotonically increasing, so it has an inverse.
Produce a function for ?(x). Be careful: rational numbers have two possible continued fraction representations:
[a0;a1,... an−1,an] and
[a0;a1,... an−1,an−1,1]
Choose one of the above that will give a binary expansion ending with a 1.
Produce the inverse function ?-1(x)
Verify that ?(φ) = 5/3, where φ is the Greek golden ratio.
Verify that ?-1(-5/9) = (√13 - 7)/6
Verify that the two functions are inverses of each other by showing that ?-1(?(x))=x and ?(?-1(y))=y for x, y of your choice
Don't worry about precision error in the last few digits.
See also
Wikipedia entry: Minkowski's question-mark function
| #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 < 0 or p < 0:
break
n = q + s
if n < 0:
break
if x < m / n:
r = m
s = n
else:
y += d
p = m
q = n
return y + d
def minkowski_inv(x):
if x > 1 or x < 0:
return math.floor(x) + minkowski_inv(x - math.floor(x))
if x == 1 or x == 0:
return x
cont_frac = [0]
current = 0
count = 1
i = 0
while True:
x *= 2
if current == 0:
if x < 1:
count += 1
else:
cont_frac.append(0)
cont_frac[i] = count
i += 1
count = 1
current = 1
x -= 1
else:
if x > 1:
count += 1
x -= 1
else:
cont_frac.append(0)
cont_frac[i] = count
i += 1
count = 1
current = 0
if x == math.floor(x):
cont_frac[i] = count
break
if i == MAXITER:
break
ret = 1.0 / cont_frac[i]
for j in range(i - 1, -1, -1):
ret = cont_frac[j] + 1.0 / ret
return 1.0 / ret
if __name__ == "__main__":
print(
"{:19.16f} {:19.16f}".format(
minkowski(0.5 * (1 + math.sqrt(5))),
5.0 / 3.0,
)
)
print(
"{:19.16f} {:19.16f}".format(
minkowski_inv(-5.0 / 9.0),
(math.sqrt(13) - 7) / 6,
)
)
print(
"{:19.16f} {:19.16f}".format(
minkowski(minkowski_inv(0.718281828)),
minkowski_inv(minkowski(0.1213141516171819)),
)
)
|
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
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #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 host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #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) // choose a door at random
var shown = 0
while (true) {
shown = rand.int(3) // the shown door
if (doors[shown] != 1 && shown != choice) break
}
stayWins = stayWins + doors[choice]
switchWins = switchWins + doors[3-choice-shown]
}
System.print("Simulating %(games) games:")
System.print("Staying wins %(stayWins) times")
System.print("Switching wins %(switchWins) times")
}
montyHall.call(1e6) |
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]
if (j >= i)
product = i * j;
"calculate spacing for right justification of values";
if (product >= 100)
spacer = "";
elseif (product >= 10)
spacer = " ";
else
spacer = " ";
endif
line = line + " " + spacer + tostr(product);
else
line = line + " ";
endif
endfor
player:tell(line);
endfor
.
|
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 random numbers to the probability given by function modifier:
while True:
random1 = rgen()
random2 = rgen()
if random2 < modifier(random1):
answer = random1
break
endif
endwhile
Task
Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:
modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5)
Create a generator of random numbers with probabilities modified by the above function.
Generate >= 10,000 random numbers subject to the probability modification.
Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.
Show your output here, on this page.
| #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 random numbers to the probability given by function modifier:
while True:
random1 = rgen()
random2 = rgen()
if random2 < modifier(random1):
answer = random1
break
endif
endwhile
Task
Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:
modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5)
Create a generator of random numbers with probabilities modified by the above function.
Generate >= 10,000 random numbers subject to the probability modification.
Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.
Show your output here, on this page.
| #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 /* " " " " " " */
if datatype(seed, 'W') then call random ,,seed /* " " " " " " */
call MRD
!.= 0
do j=1 for randN; bin= @.j*bins%1
!.bin= !.bin + 1 /*bump the applicable bin counter. */
end /*j*/
mx= 0
do k=1 for randN; mx= max(mx, !.k) /*find the maximum, used for histograph*/
end /*k*/
say ' bin'
say '────── ' center('(with ' commas(randN) " samples", 80 - 10)
do b=0 for bins; say format(b/bins,2,2) copies('■', 70*!.b%mx)" " commas(!.b)
end /*b*/
exit 0
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
rand: return random(0, 100000) / 100000
/*──────────────────────────────────────────────────────────────────────────────────────*/
modifier: parse arg y; if y<.5 then return 2 * (.5 - y)
else return 2 * ( y - .5)
/*──────────────────────────────────────────────────────────────────────────────────────*/
MRD: #=0; @.= /*MRD: Modified Random distribution. */
do until #==randN; r= rand() /*generate a random number; assign bkup*/
if rand()>=modifier(r) then iterate /*Doesn't meet requirement? Then skip.*/
#= # + 1; @.#= r /*bump counter; assign the MRD to array*/
end /*until*/
return |
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 positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #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;
LONG INT count;
INT num = n;
FOR i FROM 0 TO n - 1 DO pow[ i ] := val[ i ] := 0 OD;
count := 0;
ten := 1;
x := 1;
WHILE x < n
AND BEGIN val[ x ] := ten;
FOR j FROM 0 TO n- 1 DO
IF pow[ j ] /= 0 THEN
IF INT j plus ten mod num = ( j + ten ) MOD num;
pow[ j plus ten mod num ] = 0
THEN
IF pow[ j ] /= x THEN pow[ j plus ten mod num ] := x FI
FI
FI
OD;
IF pow[ ten ] = 0 THEN pow[ ten ] := x FI;
ten *:= 10 MODAB num;
pow[ 0 ] = 0
END
DO
x +:= 1
OD;
x := num;
IF pow[ 0 ] = 0 THEN - 1 # couldn't find B10 #
ELSE
LONG INT result := 0;
WHILE x /= 0 DO
WHILE ( count -:= 1 ) > pow[ x MOD num ] - 1 DO result *:= 10 OD;
count := pow [ x MOD num ] -1;
result *:= 10 +:= 1;
x := SHORTEN ( num + x - val[ SHORTEN pow[ x MOD num ] ] ) MOD num
OD;
WHILE count > 0 DO result *:= 10 ; count -:= 1 OD;
result
FI
FI # find B10 # ;
# outputs B10 for the specified n #
PROC show b10 = ( INT n )VOID:
IF LONG INT b10 = find b10( n );
b10 < 1
THEN print( ( "Cannot find B10 for: ", whole( n, 0 ), newline ) )
ELSE
# found B10(n) #
print( ( whole( n, -6 ), ": ", whole( b10, -32 ), " = ", whole( n, -6 ), " * ", whole( b10 OVER n, 0 ), newline ) )
FI;
# task test cases #
FOR n FROM 1 TO 10 DO show b10( n ) OD;
FOR n FROM 95 TO 105 DO show b10( n ) OD;
[]INT tests = ( 297, 576, 594, 891, 909, 999
, 1998, 2079, 2251, 2277
, 2439, 2997, 4878
);
FOR n FROM LWB tests TO UPB tests DO show b10( tests[ n ] ) OD
END
|
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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #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);
mpz_powm(r, a, b, m);
gmp_printf("%Zd\n", r); /* ...16808958343740453059 */
mpz_clear(a);
mpz_clear(b);
mpz_clear(m);
mpz_clear(r);
return 0;
} |
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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #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 = BigInteger.Pow(10, 40);
Console.WriteLine(BigInteger.ModPow(a, b, 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
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #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-int.
C: <mod-int> mod-int
ERROR: non-equal-modulus m1 m2 ;
! Define a literal syntax for mod-int.
<< SYNTAX: MI{ \ } [ first2 <mod-int> ] parse-literal ; >>
! Implement prettyprinting for mod-int custom syntax.
M: mod-int pprint-delims drop \ MI{ \ } ;
M: mod-int >pprint-sequence [ n>> ] [ mod>> ] bi { } 2sequence ;
M: mod-int pprint* pprint-object ;
<PRIVATE
! Helper words for displaying the results of an arithmetic
! operation.
: show ( quot -- )
[ unparse 2 tail but-last "= " append write ] [ call . ] bi
; inline
: 2show ( quots -- )
[ 2curry show ] map-compose [ call( -- ) ] each ; inline
! Check whether two mod-ints have the same modulus and throw an
! error if not.
: check-mod ( m1 m2 -- )
2dup [ mod>> ] bi@ = [ 2drop ] [ non-equal-modulus ] if ;
! Apply quot to the integer parts of two mod-ints and create a
! new mod-int from the result.
: mod-int-op ( m1 m2 quot -- m3 )
[ [ n>> ] bi@ ] prepose [ 2dup check-mod ] dip over
mod>> [ call( x x -- x ) ] dip [ mod ] keep <mod-int>
; inline
! Promote an integer to a mod-int and call mod-int-op.
: integer-op ( obj1 obj2 quot -- mod-int )
[
dup integer?
[ over mod>> <mod-int> ]
[ dup [ mod>> <mod-int> ] dip ] if
] dip mod-int-op ; inline
! Apply quot, a binary function, to any combination of integers
! and mod-ints.
: binary-op ( obj1 obj2 quot -- mod-int )
2over [ mod-int? ] both? [ mod-int-op ] [ integer-op ] if
; inline
PRIVATE>
! This is where the arithmetic words are 'redefined' by adding a
! method to them that specializes on the object class.
M: object + [ + ] binary-op ;
M: object - [ - ] binary-op ;
M: object * [ * ] binary-op ;
M: object /i [ /i ] binary-op ;
! ^ is a special case because it is not generic.
: ^ ( obj1 obj2 -- obj3 )
2dup [ mod-int? ] either? [ [ ** ] binary-op ] [ ** ] if ;
: fn ( obj -- obj' ) dup 100 ^ + 1 + ;
: modular-arithmetic-demo ( -- )
[ MI{ 10 13 } fn ]
[ 2 fn ] [ show ] bi@
{
[ MI{ 10 13 } MI{ 5 13 } [ + ] ]
[ MI{ 10 13 } 5 [ + ] ]
[ 5 MI{ 10 13 } [ + ] ]
[ MI{ 10 13 } 2 [ /i ] ]
[ 5 10 [ * ] ]
[ MI{ 3 7 } MI{ 4 7 } [ * ] ]
[ MI{ 3 7 } 50 [ ^ ] ]
} 2show ;
MAIN: modular-arithmetic-demo |
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 ..]
productDigitSums :: Int -> [Int]
productDigitSums n = digitSum . (n *) <$> [0 ..]
--------------------------- TEST -------------------------
main :: IO ()
main =
(putStrLn . table " ") $
chunksOf 10 $ show <$> take 40 a131382
------------------------- GENERIC ------------------------
digitSum :: Int -> Int
digitSum 0 = 0
digitSum n = uncurry (+) (first digitSum $ quotRem n 10)
table :: String -> [[String]] -> String
table gap rows =
let ws = maximum . fmap length <$> transpose rows
pw = printf . flip intercalate ["%", "s"] . show
in unlines $ intercalate gap . zipWith pw ws <$> rows |
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 perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #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 1*"1 last+"1 0/m
divs=. (2,.n,.0)+"2]0 0 1*"1 last*"1 0/n
prev=. subs,"2 divs NB. we are working backwards from 1
paths=. (,({:"1 prev)e.ok)#,/prev,"1 2/"2 paths
end.
;@((<":y),,)"2((' -/'{~{.);":@{:)"1}:"2}:"1 paths
}}
|
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 armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #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=0;i<$1;i++ ))
do
if [[ (${board[$i]}-${board[$1]} -eq ${i}-${1}) || (${board[$i]}-${board[$1]} -eq ${1}-${i}) || (${board[$i]} -eq ${board[$1]}) ]]
then
(( flag=0 ))
fi
done
[[ $flag -eq 0 ]]
return $?
}
# print the result
function out
{
printf "Problem of queen %d:%d\n" $BoardSize $total
}
# free the variables
function depose
{
unset p
unset total
unset board
unset BoardSize
}
# back tracing
function work
{
while [[ $p -gt -1 ]]
do
(( board[$p]++ ))
if [[ ${board[$p]} -ge ${BoardSize} ]]
then # back tracing
(( p-- ))
else # try next position
place $p
if [[ $? -eq 1 ]]
then
(( p++ ))
if [[ $p -ge ${BoardSize} ]]
then
(( total++ ))
(( p-- ))
else
(( board[$p]=-1 ))
fi
fi
fi
done
}
# entry
init
work
out
depose |
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 of the first zero.
Thus, ?(31/7) = 71/16 because 31/7 has the continued fraction representation [4;2,3] giving the binary expansion 4 + 0.01112.
Among its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits.
The question-mark function is continuous and monotonically increasing, so it has an inverse.
Produce a function for ?(x). Be careful: rational numbers have two possible continued fraction representations:
[a0;a1,... an−1,an] and
[a0;a1,... an−1,an−1,1]
Choose one of the above that will give a binary expansion ending with a 1.
Produce the inverse function ?-1(x)
Verify that ?(φ) = 5/3, where φ is the Greek golden ratio.
Verify that ?-1(-5/9) = (√13 - 7)/6
Verify that the two functions are inverses of each other by showing that ?-1(?(x))=x and ?(?-1(y))=y for x, y of your choice
Don't worry about precision error in the last few digits.
See also
Wikipedia entry: Minkowski's question-mark function
| #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) < 0 | $p < 0 ||
( my $n = $q + $s) < 0 ;
x < $m/$n ?? ( ($r,$s) = ($m, $n) ) !! ( $y += $d; ($p,$q) = ($m, $n) );
}
return $y + $d
}
sub minkowskiInv($x is copy) {
return $x.floor + minkowskiInv($x - $x.floor) if $x > 1 || $x < 0 ;
return $x if $x == 1 || $x == 0 ;
my @contFrac = 0;
my $i = my $curr = 0 ; my $count = 1;
loop {
$x *= 2;
if $curr == 0 {
if $x < 1 {
$count++
} else {
$i++;
@contFrac.append: 0;
@contFrac[$i-1] = $count;
($count,$curr) = 1,1;
$x--;
}
} else {
if $x > 1 {
$count++;
$x--;
} else {
$i++;
@contFrac.append: 0;
@contFrac[$i-1] = $count;
($count,$curr) = 1,0;
}
}
if $x == $x.floor { @contFrac[$i] = $count ; last }
last if $i == MAXITER;
}
my $ret = 1 / @contFrac[$i];
loop (my $j = $i - 1; $j ≥ 0; $j--) { $ret = @contFrac[$j] + 1/$ret }
return 1 / $ret
}
printf "%19.16f %19.16f\n", minkowski(0.5*(1 + 5.sqrt)), 5/3;
printf "%19.16f %19.16f\n", minkowskiInv(-5/9), (13.sqrt-7)/6;
printf "%19.16f %19.16f\n", minkowski(minkowskiInv(0.718281828)),
minkowskiInv(minkowski(0.1213141516171819)) |
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
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #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} {incr i} {
puts -nonewline [m $i];
puts -nonewline " ";
}
puts "" |
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 host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #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; //0 is a goat, 1 is a car
doors[2] = 0;
doors[3] = 0;
doors[(xGlobal::randomPositiveInt32() mod 3) + 1] = 1; //put a winner in a random door
picked = (xGlobal::randomPositiveInt32() mod 3) + 1; //pick a door, any door
do
{
reveal = (xGlobal::randomPositiveInt32() mod 3) + 1;
}
while (doors[reveal] == 1 || reveal == picked); //don't show the winner or the choice
if (doors[picked] == 1)
noChangeWins++;
else
changeWins++;
}
print strFmt("Switching wins %1 times.", changeWins);
print strFmt("Staying wins %1 times.", noChangeWins);
pause;
|
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 host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #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 door
repeat Monty:= Ran(3); \Monty opens door revealing a goat
until Monty # Car and Monty # Player0;
if Switch then \player switches to remaining door
repeat Player:= Ran(3);
until Player # Player0 and Player # Monty
else Player:= Player0; \player sticks with original door
if Player = Car then Wins:= Wins+1;
];
[Format(2,1);
Text(0, "Not switching doors wins car in ");
Wins:= 0;
for Game:= 0 to Games-1 do Play(false);
RlOut(0, float(Wins)/float(Games)*100.0);
Text(0, "% of games.^M^J");
Text(0, "But switching doors wins car in ");
Wins:= 0;
for Game:= 0 to Games-1 do Play(true);
RlOut(0, float(Wins)/float(Games)*100.0);
Text(0, "% of games.^M^J");
] |
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="" FOR I=1:1:(MW+2) SET BAR=BAR_"-"
FOR D=1:1:(SIZE+2) DO
.FOR A=1:1:(SIZE+1) DO
..WRITE:(D=1)&(A=1) !,$JUSTIFY("",MW-1)," X|"
..WRITE:(D=1)&(A>1) ?((A-1)*5),$JUSTIFY((A-1),MW)
..WRITE:(D=2)&(A=1) !,BAR
..WRITE:(D=2)&(A'=1) BAR
..WRITE:(D>2)&(A=1) !,$JUSTIFY((D-2),MW)," |"
..WRITE:((A-1)>=(D-2))&((D-2)>=1) ?((A-1)*5),$JUSTIFY((D-2)*(A-1),MW)
KILL MW,D,A,BAR
QUIT |
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 random numbers to the probability given by function modifier:
while True:
random1 = rgen()
random2 = rgen()
if random2 < modifier(random1):
answer = random1
break
endif
endwhile
Task
Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:
modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5)
Create a generator of random numbers with probabilities modified by the above function.
Generate >= 10,000 random numbers subject to the probability modification.
Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.
Show your output here, on this page.
| #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 print_histogram ( @data, :$n-bins, :$width ) { # Assumes minimum of zero.
my %counts = bag @data.map: { floor( $_ * $n-bins ) / $n-bins };
my $max_value = %counts.values.max;
sub hist { '■' x ( $width * $^count / $max_value ) }
say ' Bin, Counts: Histogram';
printf "%4.2f, %6d: %s\n", .key, .value, hist(.value) for %counts.sort;
}
my @d = modified_random_distribution( &modifier );
print_histogram( @d.head(50_000), :n-bins(20), :width(64) ); |
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 positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #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 afterwards.
set nx to n
set endZeroCount to 0
repeat with factor in {10, 5, 2}
repeat while (nx mod factor = 0)
set endZeroCount to endZeroCount + 1
set nx to nx div factor
end repeat
end repeat
script o
-- 'val' and 'pow' are uninformative and misleading labels for these lists, but I've
-- kept them for code comparison purposes and because I can't think of anything better.
property val : {} -- Will be successive powers of 10, mod nx.
property pow : {} -- Initially nx placeholders, some or all of which will be replaced with indices to slots in val.
property digits : {} -- Digits for output.
end script
if (nx = 1) then
set end of o's digits to 1 -- Clever stuff not needed.
else
set placeholder to missing value
repeat nx times
set end of o's pow to placeholder
end repeat
-- Calculate successive powers of 10, mod nx, (hereafter "powers"), storing them in val and
-- finding all the sums-mod-nx ("sums") that can be made from them and sums already obtained.
-- The range of possible sums (0 to nx - 1) is represented by positions in pow (index = sum + 1
-- with AppleScript's 1-based indices). Assign the index in val of the first power to produce
-- each sum to pow's slot for that sum. Stop when the index of the current power turns up in
-- pow's first slot, indicating that a subset of the powers obtained sums to nx (sum mod nx = 0)
-- and thus that the sum of the corresponding /un/modded powers of 10 is a multiple of nx.
-- The first power of 10 is always 1, its index in val is always 1, and its only possible sum is itself.
set p10 to 1 -- 10 ^ 0 mod nx.
set end of o's val to p10
set valIndex to 1
set item (p10 + 1) of o's pow to valIndex
-- Subsequent settings depend on the value of nx.
repeat until (beginning of o's pow = valIndex)
-- Get the next power of 10, mod nx.
set p10 to p10 * 10 mod nx
set end of o's val to p10
set valIndex to valIndex + 1
-- "Add" it to any existing sums by inserting its val index into the pow slot p10 places after (mod nx)
-- each slot already set for a lower-order p10, provided the target slot itself isn't already set.
repeat with powIndex from 1 to nx
set this to item powIndex of o's pow
if (this is placeholder) then
else if (this < valIndex) then
set targetIndex to (powIndex + p10 - 1) mod nx + 1
if (item targetIndex of o's pow is placeholder) then set item targetIndex of o's pow to valIndex
end if
end repeat
-- Ensure that it's also treated as a sum in its own right.
set targetIndex to p10 + 1
if (item targetIndex of o's pow is placeholder) then set item targetIndex of o's pow to valIndex
end repeat
-- To identify the powers-mod-nx which summed to nx, use pow unnecessarily to look up the index
-- of the power still in p10 which allowed the sum, subtract that power from the sum, use pow again
-- to find the lower-order power that allowed what's left, and so on until the sum's reduced to 0.
-- Append a 1 to the digit list for each power identified and a 0 each for any intervening ones.
set sum to nx
set previousIndex to 0
repeat until (sum = 0)
set valIndex to (item (sum mod nx + 1) of o's pow)
repeat (previousIndex - valIndex - 1) times
set end of o's digits to 0
end repeat
set end of o's digits to 1
set previousIndex to valIndex
set sum to (sum - (item valIndex of o's val) + nx) mod nx
end repeat
end if
-- Append any trailing zeros due from factors removed at the beginning.
repeat endZeroCount times
set end of o's digits to 0
end repeat
-- Coerce the list of 1s and 0s to text.
set bTen to join(o's digits, "")
-- Replace the list's contents with the results of dividing by the original n.
set digitCount to (count o's digits)
set remainder to 0
repeat with i from 1 to digitCount
set dividend to remainder * 10 + (item i of o's digits)
set item i of o's digits to dividend div n
set remainder to dividend mod n
end repeat
-- Zap any leading zeros in the result and coerce what's left to text.
repeat with i from 1 to digitCount
if (item i of o's digits > 0) then exit repeat
set item i of o's digits to ""
end repeat
set multiplier to join(o's digits, "")
return {n:n, b10:bTen, multiplier:multiplier}
end b10
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
local output, n, bTen, multiplier
set output to {}
repeat with n in {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, ¬
297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878}
set {b10:bTen, multiplier:multiplier} to b10(n's contents)
set end of output to (n as text) & " * " & multiplier & (" = " & bTen)
end repeat
return join(output, linefeed) |
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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #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("2988348162058574136915891421498819466320163312926952423791023078876139");
cpp_int b("2351399303373464486466122544523690094744975233415544072992656881240319");
std::cout << powm(a, b, pow(cpp_int(10), 40)) << '\n';
return 0;
} |
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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #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
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #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 .
: set-modulus _m ! ;
\ For A B return C GCD where C*A+x*B=GCD
: XGCD 1 0 2SWAP BEGIN OVER /MOD OVER WHILE >R SWAP
2SWAP OVER R> * - SWAP 2SWAP REPEAT 2DROP NIP ;
\ Suffix n : normalized number.
: _norm_-m DUP 0< _m @ AND + ; ( x -- xn ) \ -m<xn<+m
: +m + _m @ - _norm_-m ; ( an bn -- sumn )
: -m - _norm_-m ; ( an bn -- diffn)
: *m M* _m @ SM/REM DROP ; ( an bn -- prodn)
: /m _m @ XGCD DROP _norm_-m *m ; ( a b -- quotn)
: %:m S>D _m @ SM/REM DROP _norm_-m ; ( a -- an)
\ Both steps: For A B and C: return A B en C. Invariant A*B^C.
: _reduce_1- 1- >R >R R@ *m R> R> ;
: _reduce_2/ 2/ >R DUP *m R> ;
( a b -- apowbn )
: **m 1 ROT ROT BEGIN DUP 1 AND IF _reduce_1- THEN
_reduce_2/ DUP 0= UNTIL 2DROP ;
\ The solution is
13 set-modulus
10 DUP 100 **m +m 1 +m . CR
\ In order to comply with the problem we can generate a separate namespace
\ and import the above definitions.
VOCABULARY MODULO
ALSO MODULO DEFINITIONS
' set-modulus ALIAS set-modulus
' +m ALIAS +
' -m ALIAS -
' *m ALIAS *
' /m ALIAS /
' **m ALIAS **
' %:m ALIAS %:m
\ now the calculation becomes
13 set-modulus
10 DUP 100 ** + 1 + . CR
|
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
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #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, ringElement) ringElement
mulIdent() ringElement
}
type ringElement interface{}
// Define a power function that works for any ring.
func ringPow(r ring, a ringElement, p uint) (pow ringElement) {
for pow = r.mulIdent(); p > 0; p-- {
pow = r.mul(pow, a)
}
return
}
// The task function f has that constant 1 in it.
// Define a special kind of ring that has this element.
type oneRing interface {
ring
one() ringElement // return ring element corresponding to '1'
}
// Now define the required function f.
// It works for any ring (that has a "one.")
func f(r oneRing, x ringElement) ringElement {
return r.add(r.add(ringPow(r, x, 100), x), r.one())
}
// With rings and the function f defined in a general way, now define
// the specific ring of integers modulo n.
type modRing uint // value is congruence modulus n
func (m modRing) add(a, b ringElement) ringElement {
return (a.(uint) + b.(uint)) % uint(m)
}
func (m modRing) mul(a, b ringElement) ringElement {
return (a.(uint) * b.(uint)) % uint(m)
}
func (modRing) mulIdent() ringElement { return uint(1) }
func (modRing) one() ringElement { return uint(1) }
// Demonstrate the general function f on the specific ring with the
// specific values.
func main() {
fmt.Println(f(modRing(13), uint(10)))
} |
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 perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #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 void runTasks(List<Function> functions) {
Map<Integer,List<String>> minPath = getInitialMap(functions, 5);
// Task 1
int max = 10;
populateMap(minPath, functions, max);
System.out.printf("%nWith functions: %s%n", functions);
System.out.printf(" Minimum steps to 1:%n");
for ( int n = 2 ; n <= max ; n++ ) {
int steps = minPath.get(n).size();
System.out.printf(" %2d: %d step%1s: %s%n", n, steps, steps == 1 ? "" : "s", minPath.get(n));
}
// Task 2
displayMaxMin(minPath, functions, 2000);
// Task 2a
displayMaxMin(minPath, functions, 20000);
// Task 2a +
displayMaxMin(minPath, functions, 100000);
}
private static void displayMaxMin(Map<Integer,List<String>> minPath, List<Function> functions, int max) {
populateMap(minPath, functions, max);
List<Integer> maxIntegers = getMaxMin(minPath, max);
int maxSteps = maxIntegers.remove(0);
int numCount = maxIntegers.size();
System.out.printf(" There %s %d number%s in the range 1-%d that have maximum 'minimal steps' of %d:%n %s%n", numCount == 1 ? "is" : "are", numCount, numCount == 1 ? "" : "s", max, maxSteps, maxIntegers);
}
private static List<Integer> getMaxMin(Map<Integer,List<String>> minPath, int max) {
int maxSteps = Integer.MIN_VALUE;
List<Integer> maxIntegers = new ArrayList<Integer>();
for ( int n = 2 ; n <= max ; n++ ) {
int len = minPath.get(n).size();
if ( len > maxSteps ) {
maxSteps = len;
maxIntegers.clear();
maxIntegers.add(n);
}
else if ( len == maxSteps ) {
maxIntegers.add(n);
}
}
maxIntegers.add(0, maxSteps);
return maxIntegers;
}
private static void populateMap(Map<Integer,List<String>> minPath, List<Function> functions, int max) {
for ( int n = 2 ; n <= max ; n++ ) {
if ( minPath.containsKey(n) ) {
continue;
}
Function minFunction = null;
int minSteps = Integer.MAX_VALUE;
for ( Function f : functions ) {
if ( f.actionOk(n) ) {
int result = f.action(n);
int steps = 1 + minPath.get(result).size();
if ( steps < minSteps ) {
minFunction = f;
minSteps = steps;
}
}
}
int result = minFunction.action(n);
List<String> path = new ArrayList<String>();
path.add(minFunction.toString(n));
path.addAll(minPath.get(result));
minPath.put(n, path);
}
}
private static Map<Integer,List<String>> getInitialMap(List<Function> functions, int max) {
Map<Integer,List<String>> minPath = new HashMap<>();
for ( int i = 2 ; i <= max ; i++ ) {
for ( Function f : functions ) {
if ( f.actionOk(i) ) {
int result = f.action(i);
if ( result == 1 ) {
List<String> path = new ArrayList<String>();
path.add(f.toString(i));
minPath.put(i, path);
}
}
}
}
return minPath;
}
private static List<Function> getFunctions3() {
List<Function> functions = new ArrayList<>();
functions.add(new Divide2Function());
functions.add(new Divide3Function());
functions.add(new Subtract2Function());
functions.add(new Subtract1Function());
return functions;
}
private static List<Function> getFunctions2() {
List<Function> functions = new ArrayList<>();
functions.add(new Divide3Function());
functions.add(new Divide2Function());
functions.add(new Subtract2Function());
return functions;
}
private static List<Function> getFunctions1() {
List<Function> functions = new ArrayList<>();
functions.add(new Divide3Function());
functions.add(new Divide2Function());
functions.add(new Subtract1Function());
return functions;
}
public abstract static class Function {
abstract public int action(int n);
abstract public boolean actionOk(int n);
abstract public String toString(int n);
}
public static class Divide2Function extends Function {
@Override public int action(int n) {
return n/2;
}
@Override public boolean actionOk(int n) {
return n % 2 == 0;
}
@Override public String toString(int n) {
return "/2 -> " + n/2;
}
@Override public String toString() {
return "Divisor 2";
}
}
public static class Divide3Function extends Function {
@Override public int action(int n) {
return n/3;
}
@Override public boolean actionOk(int n) {
return n % 3 == 0;
}
@Override public String toString(int n) {
return "/3 -> " + n/3;
}
@Override public String toString() {
return "Divisor 3";
}
}
public static class Subtract1Function extends Function {
@Override public int action(int n) {
return n-1;
}
@Override public boolean actionOk(int n) {
return true;
}
@Override public String toString(int n) {
return "-1 -> " + (n-1);
}
@Override public String toString() {
return "Subtractor 1";
}
}
public static class Subtract2Function extends Function {
@Override public int action(int n) {
return n-2;
}
@Override public boolean actionOk(int n) {
return n > 2;
}
@Override public String toString(int n) {
return "-2 -> " + (n-2);
}
@Override public String toString() {
return "Subtractor 2";
}
}
}
|
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 armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #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+ remove_reflections+ ~&rSSs+ nleq-<&l*rFlhthPXPSPS,
~&i&& ~&lNrNCXX; ~&rr->rl ^/~&l ~&lrrhrSiF4E?/~&rrlPlCrtPX @r ^|/~& ^|T\~& -+
-<&l^|*DlrTS/~& ~&iiDlSzyCK9hlPNNXXtCS,
^jrX/~& @rZK20lrpblPOlrEkPK13lhPK2 ~&i&& nleq$-&lh+-,
^/~&NNXS+iota -<&l+ ~&plll2llr2lrPrNCCCCNXS*=irSxPSp+ ^H/block iota; *iiK0 ^/~& sum+- |
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 of the first zero.
Thus, ?(31/7) = 71/16 because 31/7 has the continued fraction representation [4;2,3] giving the binary expansion 4 + 0.01112.
Among its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits.
The question-mark function is continuous and monotonically increasing, so it has an inverse.
Produce a function for ?(x). Be careful: rational numbers have two possible continued fraction representations:
[a0;a1,... an−1,an] and
[a0;a1,... an−1,an−1,1]
Choose one of the above that will give a binary expansion ending with a 1.
Produce the inverse function ?-1(x)
Verify that ?(φ) = 5/3, where φ is the Greek golden ratio.
Verify that ?-1(-5/9) = (√13 - 7)/6
Verify that the two functions are inverses of each other by showing that ?-1(?(x))=x and ?(?-1(y))=y for x, y of your choice
Don't worry about precision error in the last few digits.
See also
Wikipedia entry: Minkowski's question-mark function
| #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( minkI(0.718281828) ) ) fmt( mink( minkI(.1213141516171819) ) )
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
floor: procedure; parse arg x; t= trunc(x); return t - (x<0) * (x\=t)
fmt: procedure: parse arg a; d= digits(); return right( format(a, , d-2, 0), d+5)
/*──────────────────────────────────────────────────────────────────────────────────────*/
mink: procedure: parse arg x; p= x % 1; if x>1 | x<0 then return p + mink(x-p)
q= 1; s= 1; m= 0; n= 0; d= 1; y= p
r= p + 1
do forever; d= d * 0.5; if y+d=y | d=0 then leave /*d= d÷2*/
m= p + r; if m<0 | p<0 then leave
n= q + s; if n<0 then leave
if x<m/n then do; r= m; s= n; end
else do; y= y + d; p= m; q= n; end
end /*forever*/
return y + d
/*──────────────────────────────────────────────────────────────────────────────────────*/
minkI: procedure; parse arg x; p= floor(x); if x>1 | x<0 then return p + minkI(x-p)
if x=1 | x=0 then return x
cur= 0; limit= 200; $= /*limit: max iterations*/
#= 1 /*#: is the count. */
do until #==limit | words($)==limit; x= x * 2
if cur==0 then if x<1 then #= # + 1
else do; $= $ #; #= 1; cur= 1; x= x-1; end
else if x>1 then do; #= # + 1; x= x-1; end
else do; $= $ #; #= 1; cur= 0; end
if x==floor(x) then do; $= $ #; leave; end
end /*until*/
z= words($)
ret= 1 / word($, z)
do j=z for z by -1; ret= word($, j) + 1 / ret
end /*j*/
return 1 / ret
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6
numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g=g *.5'e'_ %2
do j=0 while h>9; m.j= h; h= h % 2 + 1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g= (g + x/g) * .5; end /*k*/; return g |
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
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #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 host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #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_elegida then permanece = permanece + 1 : fi
// cambiar elección
if pta_coche = 6 - pta_montys - pta_elegida then cambia = cambia + 1 : fi
next i
print "Si mantiene su eleccion, tiene un ", permanece / numTiradas * 100, "% de probabilidades de ganar."
print "Si cambia, tiene un ", cambia / numTiradas * 100, "% de probabilidades de ganar."
end
|
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 host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #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 += doors[3 - choice - shown];
keeperWins += doors[choice];
}
"Switcher Wins: %,d (%3.2f%%)".fmt(
switcherWins, switcherWins.toFloat() / games * 100).println();
"Keeper Wins: %,d (%3.2f%%)".fmt(
keeperWins, keeperWins.toFloat() / games * 100).println(); |
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 {
$print("----");
i += 1;
}
$print("\n");
j = 1;
while j < 13 {
$print(sprintf("%3d", j));
$print(" |");
i = 1;
while i < 13 {
if j > i {
$print(" ");
} else {
$print(sprintf("%4d", i*j));
}
i += 1;
}
$print("\n");
j += 1;
} |
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 random numbers to the probability given by function modifier:
while True:
random1 = rgen()
random2 = rgen()
if random2 < modifier(random1):
answer = random1
break
endif
endwhile
Task
Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:
modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5)
Create a generator of random numbers with probabilities modified by the above function.
Generate >= 10,000 random numbers subject to the probability modification.
Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.
Show your output here, on this page.
| #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) : 2 * (x - 0.5) }
var N = 100000
var NUM_BINS = 20
var HIST_CHAR = "■"
var HIST_CHAR_SIZE = 125
var bins = List.filled(NUM_BINS, 0)
var binSize = 1 / NUM_BINS
for (i in 0...N) {
var rn = rng.call(modifier)
var bn = (rn / binSize).floor
bins[bn] = bins[bn] + 1
}
Fmt.print("Modified random distribution with $,d samples in range [0, 1):\n", N)
System.print(" Range Number of samples within that range")
for (i in 0...NUM_BINS) {
var hist = HIST_CHAR * (bins[i] / HIST_CHAR_SIZE).round
Fmt.print("$4.2f ..< $4.2f $s $,d", binSize * i, binSize * (i + 1), hist, bins[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 positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #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;
}
res = b;
while (n > 1) {
res *= b;
n--;
}
return res;
}
__int128 imod(__int128 m, __int128 n) {
__int128 result = m % n;
if (result < 0) {
result += n;
}
return result;
}
bool valid(__int128 n) {
if (n < 0) {
return false;
}
while (n > 0) {
int r = n % 10;
if (r > 1) {
return false;
}
n /= 10;
}
return true;
}
__int128 mpm(const __int128 n) {
__int128 *L;
__int128 m, k, r, j;
if (n == 1) {
return 1;
}
L = calloc(n * n, sizeof(__int128));
L[0] = 1;
L[1] = 1;
m = 0;
while (true) {
m++;
if (L[(m - 1) * n + imod(-ipow(10, m), n)] == 1) {
break;
}
L[m * n + 0] = 1;
for (k = 1; k < n; k++) {
L[m * n + k] = imax(L[(m - 1) * n + k], L[(m - 1) * n + imod(k - ipow(10, m), n)]);
}
}
r = ipow(10, m);
k = imod(-r, n);
for (j = m - 1; j >= 1; j--) {
if (L[(j - 1) * n + k] == 0) {
r = r + ipow(10, j);
k = imod(k - ipow(10, j), n);
}
}
if (k == 1) {
r++;
}
return r / n;
}
void print128(__int128 n) {
char buffer[64]; // more then is needed, but is nice and round;
int pos = (sizeof(buffer) / sizeof(char)) - 1;
bool negative = false;
if (n < 0) {
negative = true;
n = -n;
}
buffer[pos] = 0;
while (n > 0) {
int rem = n % 10;
buffer[--pos] = rem + '0';
n /= 10;
}
if (negative) {
buffer[--pos] = '-';
}
printf(&buffer[pos]);
}
void test(__int128 n) {
__int128 mult = mpm(n);
if (mult > 0) {
print128(n);
printf(" * ");
print128(mult);
printf(" = ");
print128(n * mult);
printf("\n");
} else {
print128(n);
printf("(no solution)\n");
}
}
int main() {
int i;
// 1-10 (inclusive)
for (i = 1; i <= 10; i++) {
test(i);
}
// 95-105 (inclusive)
for (i = 95; i <= 105; i++) {
test(i);
}
test(297);
test(576);
test(594); // needs a larger number type (64 bits signed)
test(891);
test(909);
test(999); // needs a larger number type (87 bits signed)
// optional
test(1998);
test(2079);
test(2251);
test(2277);
// stretch
test(2439);
test(2997);
test(4878);
return 0;
} |
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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #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))
((zerop power) product)
;; Square base, and divide power by 2, until power becomes odd.
(do () ((oddp power))
(setq base (mod (* base base) divisor)
power (ash power -1)))
(setq product (mod (* product base) divisor)
power (1- power))))
(let ((a 2988348162058574136915891421498819466320163312926952423791023078876139)
(b 2351399303373464486466122544523690094744975233415544072992656881240319))
(format t "~A~%" (rosetta-mod-expt a b (expt 10 40)))) |
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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #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 = "2988348162058574136915891421498819466320163312926952423791023078876139".to_big_i
b = "2351399303373464486466122544523690094744975233415544072992656881240319".to_big_i
m = 10.to_big_i ** 40
puts a.powmod(b, 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
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #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 -> ℤ/13
f x = x^100 + x + 1
main :: IO ()
main = print (f 10) |
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
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #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
V = X
DIGIT WHENEVER V.E.0, FUNCTION RETURN SUM
W = V/10
SUM = SUM + V - W*10
V = W
TRANSFER TO DIGIT
END OF FUNCTION
END OF PROGRAM |
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] of Uint32;
DtgPartSums :array[0..7] of Uint32;
DgtSumBefore :array[0..7] of Uint32;
procedure Init_SoD;
var
d0,d1,i,j : NativeInt;
begin
i := 0;
For d1 := 0 to BASE-1 do
For d0 := 0 to BASE-1 do
begin SoD[i]:= d1+d0;inc(i); end;
j := Base*Base;
For i := 1 to Base*Base-1 do
For d1 := 0 to BASE-1 do
For d0 := 0 to BASE-1 do
begin
SoD[j] := SoD[i]+d1+d0;
inc(j);
end;
end;
procedure OutDgt;
var
i : integer;
begin
for i := 5 downto 0 do
write(DtgBase4[i]:4);
writeln;
for i := 5 downto 0 do
write(DtgPartSums[i]:4);
writeln;
for i := 5 downto 0 do
write(DgtSumBefore[i]:4);
writeln;
end;
procedure InitDigitSums(m:NativeUint);
var
n,i,s: NativeUint;
begin
//constructing minimal number with sum of digits = m ;k+9+9+9+9+9+9
//21 -> 299
n := m;
if n>BASE then
begin
i := 1;
while n>BASE-1 do
begin
i *= BASE;
dec(n,BASE-1);
end;
n := i*(n+1)-1;
//make n multiple of m
n := (n div m)*m;
//m ending in 0
i := m;
while i mod BASE = 0 do
begin
n *= BASE;
i := i div BASE;
end;
end;
For i := 0 to 4 do
begin
s := n MOD BASE4;
DtgBase4[i] := s;
DtgPartSums[i] := SoD[s];
n := (n-s) DIV BASE4;
end;
s := 0;
For i := 3 downto 0 do
begin
s += DtgPartSums[i+1];
DgtSumBefore[i]:= s;
end;
end;
function CorrectSums(sum:NativeUint):NativeUint;
var
i,q,carry : NativeInt;
begin
i := 0;
q := sum MOD Base4;
sum := sum DIV Base4;
result := q;
DtgBase4[i] := q;
DtgPartSums[i] := SoD[q];
carry := 0;
repeat
inc(i);
q := sum MOD Base4+DtgBase4[i]+carry;
sum := sum DIV Base4;
carry := 0;
if q >= BASE4 then
begin
carry := 1;
q -= BASE4;
end;
DtgBase4[i]:= q;
DtgPartSums[i] := SoD[q];
until (sum =0) AND( carry = 0);
sum := 0;
For i := 3 downto 0 do
begin
sum += DtgPartSums[i+1];
DgtSumBefore[i]:= sum;
end;
end;
function TakeJump(dgtSum,m:NativeUint):NativeUint;
var
n,i,j,carry : nativeInt;
begin
i := dgtsum div MAXDGTSUM4-1;
n := 0;
j := 1;
for i := i downto 0 do
Begin
n:= n*BASE4+DtgBase4[i];
j:= j*BASE4;
end;
n := ((j-n) DIV m)*m;
// writeln(n:10,DtgBase4[i]:10);
i := 0;
carry := 0;
repeat
j := DtgBase4[i]+ n mod BASE4 +carry;
n := n div BASE4;
carry := 0;
IF j >=BASE4 then
begin
j -= BASE4;
carry := 1;
end;
DtgBase4[i] := j;
DtgPartSums[i]:= SoD[j];
inc(i);
until (n= 0) AND (carry=0);
j := 0;
For i := 3 downto 0 do
begin
j += DtgPartSums[i+1];
DgtSumBefore[i]:= j;
end;
result := DtgBase4[0];
end;
procedure CalcN(m:NativeUint);
var
dgtsum,sum: NativeInt;
begin
InitDigitSums(m);
sum := DtgBase4[0];
dgtSum:= m-DgtSumBefore[0];
// while dgtsum+SoD[sum] <> m do
while dgtsum<>SoD[sum] do
begin
inc(sum,m);
if sum >= BASE4 then
begin
sum := CorrectSums(sum);
dgtSum:= m-DgtSumBefore[0];
if dgtSum > MAXDGTSUM4 then
begin
sum := TakeJump(dgtSum,m);
dgtSum:= m-DgtSumBefore[0];
end;
end;
end;
DtgBase4[0] := sum;
end;
var
T0:INt64;
i : NativeInt;
m,n: NativeUint;
Begin
T0 := GetTickCount64;
Init_SoD;
for m := 1 to 70 do
begin
CalcN(m);
//Check sum of digits
n := SoD[DtgBase4[4]];
For i := 3 downto 0 do
n += SoD[DtgBase4[i]];
If n<>m then
begin
writeln('ERROR at ',m);
HALT(-1);
end;
n := DtgBase4[4];
For i := 3 downto 0 do
n := n*BASE4+DtgBase4[i];
write(n DIV m :15);
if m mod 10 = 0 then
writeln;
end;
writeln;
writeln('Total runtime ',GetTickCount64-T0,' ms');
{$IFDEF WINDOWS} readln{$ENDIF}
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 perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #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, maxsteps=100000)
solutions, numsteps = Vector{Vector{ActionOutcome}}(), 0
seqs = [ActionOutcome[ActionOutcome(Action(div, 0), start)]]
if start == goal
verbose && println("For start of $start, no steps needed.\n")
return 0
end
while numsteps < maxsteps && isempty(solutions)
newsequences = Vector{Vector{ActionOutcome}}()
numsteps += 1
for seq in seqs
for (act, arr) in actions, x in arr
result = act(seq[end].out, x)
if !fails(result)
newactionseq = vcat(seq, ActionOutcome(Action(act, x), result))
numsteps == 1 && popfirst!(newactionseq)
if result == goal
push!(solutions, newactionseq)
else
push!(newsequences, newactionseq)
end
end
end
if !verbose && isempty(solutions) &&
all(x -> haskey(memoized, x[end].out), newsequences)
minresult = minimum(x -> memoized[x[end].out], newsequences) + numsteps
memoized[start] = minresult
return minresult
end
end
seqs = newsequences
end
if verbose
l = length(solutions)
print("There ", l > 1 ? "are $l solutions" : "is $l solution",
" for path of length ", numsteps, " from $start to $goal.\nExample: ")
for step in solutions[1]
print(step, step.out == 1 ? "\n\n" : ", ")
end
end
memoized[start] = numsteps
return numsteps
end
failed(n) = n < 1
const divisors = [2, 3]
divide(n, x) = begin q, r = divrem(n, x); r == 0 ? q : -1 end
const subtractors1, subtractors2 = [1], [2]
subtract(n, x) = n - x
actions1 = Dict(divide => divisors, subtract => subtractors1)
actions2 = Dict(divide => divisors, subtract => subtractors2)
function findmaxshortest(g, fails, acts, maxn)
stepcounts = [findshortest(n, g, fails, acts, false) for n in 1:maxn]
maxs = maximum(stepcounts)
maxstepnums = findall(x -> x == maxs, stepcounts)
println("There are $(length(maxstepnums)) with $maxs steps for start between 1 and $maxn: ", maxstepnums)
end
function teststeps(g, fails, acts, maxes)
println("\nWith goal $g, divisors $(acts[divide]), subtractors $(acts[subtract]):")
for n in 1:10
findshortest(n, g, fails, acts)
end
for maxn in maxes
findmaxshortest(g, fails, acts, maxn)
end
end
teststeps(1, failed, actions1, [2000, 20000, 50000])
empty!(memoized)
teststeps(1, failed, actions2, [2000, 20000, 50000])
|
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 perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #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[n, 3],
out = steps~Join~{" /3=> ", n/3};
MinimalStepToOneHelper[out]
];
If[Divisible[n, 2],
out = steps~Join~{" /2=> ", n/2};
MinimalStepToOneHelper[out]
];
If[n > 1,
out = steps~Join~{" -1=> ", n - 1};
MinimalStepToOneHelper[out]
];
]
]
Do[
sel = First[MinimalStepToOne[i]];
Print[First[sel],
": (" <> ToString[(Length[sel] - 1)/2] <> " steps) ", sel // Row]
,
{i, 1, 10}
]
$RecursionLimit = 3000;
ClearAll[MinimalStepToOne2, MinimalStepToOneHelper2]
MinimalStepToOne2[nn_Integer] :=
Module[{res, done, solution, maxsteps},
done = False;
solution = {};
MinimalStepToOneHelper2[steps_List] := Module[{n, out},
n = Last[steps];
If[n == 1,
solution = steps;
,
If[solution === {},
If[Divisible[n, 3],
out = steps~Join~{" /3=> ", n/3};
MinimalStepToOneHelper2[out]
];
If[Divisible[n, 2],
out = steps~Join~{" /2=> ", n/2};
MinimalStepToOneHelper2[out]
];
If[n > 1,
out = steps~Join~{" -1=> ", n - 1};
MinimalStepToOneHelper2[out]
];
];
];
];
MinimalStepToOneHelper2[{nn}];
maxsteps = (Length[solution] - 1)/2;
maxsteps
]
$RecursionLimit = 3000;
ClearAll[MinimalStepToOneMaxSteps, MinimalStepToOneMaxStepsHelper]
MinimalStepToOneMaxSteps[n_Integer, maxsteps_Integer] :=
Module[{res},
res = Reap[MinimalStepToOneMaxStepsHelper[{n}, maxsteps]][[-1, 1]];
(Min[Length /@ res] - 1)/2
]
MinimalStepToOneMaxStepsHelper[steps_List, maxsteps_Integer] :=
Module[{n, out},
n = Last[steps];
If[n == 1,
Sow[steps];
,
If[maxsteps > 0,
If[Divisible[n, 3],
out = steps~Join~{" /3=> ", n/3};
MinimalStepToOneMaxStepsHelper[out, maxsteps - 1]
];
If[Divisible[n, 2],
out = steps~Join~{" /2=> ", n/2};
MinimalStepToOneMaxStepsHelper[out, maxsteps - 1]
];
If[n > 1,
out = steps~Join~{" -1=> ", n - 1};
MinimalStepToOneMaxStepsHelper[out, maxsteps - 1]
];
];
];
]
allsols = Table[
max = MinimalStepToOne2[i];
{i, MinimalStepToOneMaxSteps[i, max]}
,
{i, 1, 2000}
];
a = Last[SortBy[GatherBy[allsols, Last], First /* Last]];
{a[[1, 2]], a[[All, 1]]}
$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[n, 3],
out = steps~Join~{" /3=> ", n/3};
MinimalStepToOneHelper[out]
];
If[Divisible[n, 2],
out = steps~Join~{" /2=> ", n/2};
MinimalStepToOneHelper[out]
];
If[n > 2,
out = steps~Join~{" -2=> ", n - 2};
MinimalStepToOneHelper[out]
];
]
]
Do[
sel = First[MinimalStepToOne[i]];
Print[First[sel],
": (" <> ToString[(Length[sel] - 1)/2] <> " steps) ", sel // Row]
,
{i, 1, 10}
]
$RecursionLimit = 3000;
ClearAll[MinimalStepToOne2, MinimalStepToOneHelper2]
MinimalStepToOne2[nn_Integer] :=
Module[{res, done, solution, maxsteps},
done = False;
solution = {};
MinimalStepToOneHelper2[steps_List] := Module[{n, out},
n = Last[steps];
If[n == 1,
solution = steps;
,
If[solution === {},
If[Divisible[n, 3],
out = steps~Join~{" /3=> ", n/3};
MinimalStepToOneHelper2[out]
];
If[Divisible[n, 2],
out = steps~Join~{" /2=> ", n/2};
MinimalStepToOneHelper2[out]
];
If[n > 2,
out = steps~Join~{" -2=> ", n - 2};
MinimalStepToOneHelper2[out]
];
];
];
];
MinimalStepToOneHelper2[{nn}];
maxsteps = (Length[solution] - 1)/2;
maxsteps
]
$RecursionLimit = 3000;
ClearAll[MinimalStepToOneMaxSteps, MinimalStepToOneMaxStepsHelper]
MinimalStepToOneMaxSteps[n_Integer, maxsteps_Integer] :=
Module[{res},
res = Reap[MinimalStepToOneMaxStepsHelper[{n}, maxsteps]][[-1, 1]];
(Min[Length /@ res] - 1)/2
]
MinimalStepToOneMaxStepsHelper[steps_List, maxsteps_Integer] :=
Module[{n, out},
n = Last[steps];
If[n == 1,
Sow[steps];
,
If[maxsteps > 0,
If[Divisible[n, 3],
out = steps~Join~{" /3=> ", n/3};
MinimalStepToOneMaxStepsHelper[out, maxsteps - 1]
];
If[Divisible[n, 2],
out = steps~Join~{" /2=> ", n/2};
MinimalStepToOneMaxStepsHelper[out, maxsteps - 1]
];
If[n > 2,
out = steps~Join~{" -2=> ", n - 2};
MinimalStepToOneMaxStepsHelper[out, maxsteps - 1]
];
];
];
]
allsols = Table[
max = MinimalStepToOne2[i];
{i, MinimalStepToOneMaxSteps[i, max]}
,
{i, 1, 2000}
];
a = Last[SortBy[GatherBy[allsols, Last], First /* Last]];
{a[[1, 2]], a[[All, 1]]} |
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 armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #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
j = 0
r = 2 * n - 1
Do
i = i - 1
j = j + 1
p = 0
q = -r
Do
i = i + 1
u(p) = 1
u(q + r) = 1
z = a(j): a(j) = a(i): a(i) = z 'Swap a(i), a(j)
p = i - a(i) + n
q = i + a(i) - 1
s(i) = j
j = i + 1
Loop Until j > n Or u(p) Or u(q + r)
If u(p) = 0 Then
If u(q + r) = 0 Then
m = m + 1 'm: number of solutions
If b Then
Debug.Print "n="; n; "m="; m
For k = 1 To n
For t = 1 To n
Debug.Print IIf(a(n - k + 1) = t, "Q", ".");
Next t
Debug.Print
Next k
End If
End If
End If
j = s(i)
Do While j >= n And i <> 0
Do
z = a(j): a(j) = a(i): a(i) = z 'Swap a(i), a(j)
j = j - 1
Loop Until j < i
i = i - 1
p = i - a(i) + n
q = i + a(i) - 1
j = s(i)
u(p) = 0
u(q + r) = 0
Loop
Loop Until i = 0
Debug.Print n, m 'number of queens, number of solutions
Next n
End Sub 'n_queens |
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 of the first zero.
Thus, ?(31/7) = 71/16 because 31/7 has the continued fraction representation [4;2,3] giving the binary expansion 4 + 0.01112.
Among its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits.
The question-mark function is continuous and monotonically increasing, so it has an inverse.
Produce a function for ?(x). Be careful: rational numbers have two possible continued fraction representations:
[a0;a1,... an−1,an] and
[a0;a1,... an−1,an−1,1]
Choose one of the above that will give a binary expansion ending with a 1.
Produce the inverse function ?-1(x)
Verify that ?(φ) = 5/3, where φ is the Greek golden ratio.
Verify that ?-1(-5/9) = (√13 - 7)/6
Verify that the two functions are inverses of each other by showing that ?-1(?(x))=x and ?(?-1(y))=y for x, y of your choice
Don't worry about precision error in the last few digits.
See also
Wikipedia entry: Minkowski's question-mark function
| #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 (y + d == y) break
var m = p + r
if (m < 0 || p < 0 ) break
var n = q + s
if (n < 0) break
if (x < m/n) {
r = m
s = n
} else {
y = y + d
p = m
q = n
}
}
return y + d
}
var minkowskiInv
minkowskiInv = Fn.new { |x|
if (x > 1 || x < 0) return x.floor + minkowskiInv.call(x - x.floor)
if (x == 1 || x == 0) return x
var contFrac = [0]
var curr = 0
var count = 1
var i = 0
while (true) {
x = x * 2
if (curr == 0) {
if (x < 1) {
count = count + 1
} else {
i = i + 1
var t = contFrac
contFrac = List.filled(i + 1, 0)
for (j in 0...t.count) contFrac[j] = t[j]
contFrac[i-1] = count
count = 1
curr = 1
x = x - 1
}
} else {
if (x > 1) {
count = count + 1
x = x - 1
} else {
i = i + 1
var t = contFrac
contFrac = List.filled(i + 1, 0)
for (j in 0...t.count) contFrac[j] = t[j]
contFrac[i-1] = count
count = 1
curr = 0
}
}
if (x == x.floor) {
contFrac[i] = count
break
}
if (i == MAXITER) break
}
var ret = 1/contFrac[i]
for (j in i-1..0) ret = contFrac[j] + 1/ret
return 1/ret
}
Fmt.print("$17.16f $17.14f", minkowski.call(0.5 * (1 + 5.sqrt)), 5/3)
Fmt.print("$17.14f $17.14f", minkowskiInv.call(-5/9), (13.sqrt - 7)/6)
Fmt.print("$17.14f $17.14f", minkowski.call(minkowskiInv.call(0.718281828)),
minkowskiInv.call(minkowski.call(0.1213141516171819))) |
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
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #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 positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #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[j] != x && pow[t = (j + ten) % n] == 0)
pow[t] = x;
if (pow[ten] == 0) pow[ten] = x;
ten = (10 * ten) % n;
if (pow[0] != 0) {
x = n;
string s = "";
while (x != 0) {
int p = pow[x % n];
if (count > p) s += new string('0', count - p);
count = p - 1;
s += "1";
x = (n + x - val[p]) % n;
}
if (count > 0) s += new string('0', count);
return s;
}
}
return "1";
}
static void Main(string[] args) {
string fmt = "{0,4} * {1,24} = {2,-28}\n";
int[] m = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878 };
string[] r = new string[m.Length];
WriteLine(fmt + new string('-', 62), "n", "multiplier", "B10");
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < m.Length; i++) r[i] = B10(m[i]);
sw.Stop();
for (int i = 0; i < m.Length; i++) Write(fmt, m[i], decimal.Parse(r[i]) / m[i], r[i]);
Write("\nTook {0}ms", sw.Elapsed.TotalMilliseconds);
}
} |
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
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #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;
exponent /= 2;
base = base ^^ 2 % modulus;
}
return result;
}
version (modular_exponentiation)
void main() {
import std.stdio;
powMod(BigInt("29883481620585741369158914214988194" ~
"66320163312926952423791023078876139"),
BigInt("235139930337346448646612254452369009" ~
"4744975233415544072992656881240319"),
BigInt(10) ^^ 40).writeln;
} |
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
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #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 greater");
}
int pp = p;
Ring<T> pwr = this.one();
while (pp-- > 0) {
pwr = pwr.times(this);
}
return pwr;
}
}
private static class ModInt implements Ring<ModInt> {
private int value;
private int modulo;
private ModInt(int value, int modulo) {
this.value = value;
this.modulo = modulo;
}
@Override
public Ring<ModInt> plus(Ring<ModInt> other) {
if (!(other instanceof ModInt)) {
throw new IllegalArgumentException("Cannot add an unknown ring.");
}
ModInt rhs = (ModInt) other;
if (modulo != rhs.modulo) {
throw new IllegalArgumentException("Cannot add rings with different modulus");
}
return new ModInt((value + rhs.value) % modulo, modulo);
}
@Override
public Ring<ModInt> times(Ring<ModInt> other) {
if (!(other instanceof ModInt)) {
throw new IllegalArgumentException("Cannot multiple an unknown ring.");
}
ModInt rhs = (ModInt) other;
if (modulo != rhs.modulo) {
throw new IllegalArgumentException("Cannot multiply rings with different modulus");
}
return new ModInt((value * rhs.value) % modulo, modulo);
}
@Override
public int value() {
return value;
}
@Override
public Ring<ModInt> one() {
return new ModInt(1, modulo);
}
@Override
public String toString() {
return String.format("ModInt(%d, %d)", value, modulo);
}
}
private static <T> Ring<T> f(Ring<T> x) {
return x.pow(100).plus(x).plus(x.one());
}
public static void main(String[] args) {
ModInt x = new ModInt(10, 13);
Ring<ModInt> y = f(x);
System.out.print("x ^ 100 + x + 1 for x = ModInt(10, 13) is ");
System.out.println(y);
System.out.flush();
}
} |
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,"%-8d%s",{m,iff(remainder(c,10)=0?"\n":"")})
n += 1
end while
|
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.