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/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Elena
Elena
import extensions; import system'routines;   public program() { var dataset := new object[] { new { Name = "Lagos"; Population = 21.0r; }, new { Name = "Cairo"; Population = 15.2r; }, new { Name = "Kinshasa-Brazzaville"; Population = 11.3r; }, new { Name = "Greater Johannesburg"; Population = 7.55r; }, new { Name = "Mogadishu"; Population = 5.85r; }, new { Name = "Khartoum-Omdurman"; Population = 4.98r; }, new { Name = "Dar Es Salaam"; Population = 4.7r; }, new { Name = "Alexandria"; Population = 4.58r; }, new { Name = "Abidjan"; Population = 4.4r; }, new { Name = "Casablanca"; Population = 3.98r; } };   var index := dataset.selectBy:(r => r.Name).toArray().indexOfElement("Dar Es Salaam"); console.printLine(index);   var name := dataset.filterBy:(c => c.Population < 5.0r).toArray().FirstMember.Name; console.printLine(name);   var namePopulation := dataset.filterBy:(c => c.Name.startingWith("A")).toArray().FirstMember.Population; console.printLine(namePopulation) }
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Hare
Hare
use fmt; use math;   type interval = struct {a: f64, b: f64};   export fn main() void = { const a: [_](f64, f64) = [ (1.0f64, 2.0f64), (0.1f64, 0.2f64), (1e100f64, 1e-100f64), (1e308f64, 1e308f64)];   for (let i = 0z; i < len(a); i += 1) { let res = safe_add(a[i].0, a[i].1); fmt::printfln("{} + {} is within ({}, {})", a[i].0, a[i].1, res.a, res.b)!; }; };   fn safe_add(a: f64, b: f64) interval = { let orig = math::getround(); math::setround(math::fround::DOWNWARD); let r0 = a + b; math::setround(math::fround::UPWARD); let r1 = a + b; math::setround(orig); return interval{a = r0, b = r1}; };
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#J
J
err =. 2^ 53-~ 2 <.@^. | NB. get the size of one-half unit in the last place safeadd =. + (-,+) +&err 0j15": 1.14 safeadd 2000.0 NB. print with 15 digits after the decimal 2001.139999999999873 2001.140000000000327
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Java
Java
public class SafeAddition { private static double stepDown(double d) { return Math.nextAfter(d, Double.NEGATIVE_INFINITY); }   private static double stepUp(double d) { return Math.nextUp(d); }   private static double[] safeAdd(double a, double b) { return new double[]{stepDown(a + b), stepUp(a + b)}; }   public static void main(String[] args) { double a = 1.2; double b = 0.03; double[] result = safeAdd(a, b); System.out.printf("(%.2f + %.2f) is in the range %.16f..%.16f", a, b, result[0], result[1]); } }
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#ACL2
ACL2
(defun index-of-r (e xs i) (cond ((endp xs) nil) ((equal e (first xs)) i) (t (index-of-r e (rest xs) (1+ i)))))   (defun index-of (e xs) (index-of-r e xs 0))
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#C.23
C#
using static System.Console; using System; using System.Collections; using System.Collections.Generic; using System.Linq;   public static class SafePrimes { public static void Main() { HashSet<int> primes = Primes(10_000_000).ToHashSet(); WriteLine("First 35 safe primes:"); WriteLine(string.Join(" ", primes.Where(IsSafe).Take(35))); WriteLine($"There are {primes.TakeWhile(p => p < 1_000_000).Count(IsSafe):n0} safe primes below {1_000_000:n0}"); WriteLine($"There are {primes.TakeWhile(p => p < 10_000_000).Count(IsSafe):n0} safe primes below {10_000_000:n0}"); WriteLine("First 40 unsafe primes:"); WriteLine(string.Join(" ", primes.Where(IsUnsafe).Take(40))); WriteLine($"There are {primes.TakeWhile(p => p < 1_000_000).Count(IsUnsafe):n0} unsafe primes below {1_000_000:n0}"); WriteLine($"There are {primes.TakeWhile(p => p < 10_000_000).Count(IsUnsafe):n0} unsafe primes below {10_000_000:n0}");   bool IsSafe(int prime) => primes.Contains(prime / 2); bool IsUnsafe(int prime) => !primes.Contains(prime / 2); }   //Method from maths library static IEnumerable<int> Primes(int bound) { if (bound < 2) yield break; yield return 2;   BitArray composite = new BitArray((bound - 1) / 2); int limit = ((int)(Math.Sqrt(bound)) - 1) / 2; for (int i = 0; i < limit; i++) { if (composite[i]) continue; int prime = 2 * i + 3; yield return prime; for (int j = (prime * prime - 2) / 2; j < composite.Count; j += prime) composite[j] = true; } for (int i = limit; i < composite.Count; i++) { if (!composite[i]) yield return 2 * i + 3; } }   }
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#J
J
sameFringe=: -:&([: ; <S:0)
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#Java
Java
import java.util.*;   class SameFringe { public interface Node<T extends Comparable<? super T>> { Node<T> getLeft(); Node<T> getRight(); boolean isLeaf(); T getData(); }   public static class SimpleNode<T extends Comparable<? super T>> implements Node<T> { private final T data; public SimpleNode<T> left; public SimpleNode<T> right;   public SimpleNode(T data) { this(data, null, null); }   public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right) { this.data = data; this.left = left; this.right = right; }   public Node<T> getLeft() { return left; }   public Node<T> getRight() { return right; }   public boolean isLeaf() { return ((left == null) && (right == null)); }   public T getData() { return data; }   public SimpleNode<T> addToTree(T data) { int cmp = data.compareTo(this.data); if (cmp == 0) throw new IllegalArgumentException("Same data!"); if (cmp < 0) { if (left == null) return (left = new SimpleNode<T>(data)); return left.addToTree(data); } if (right == null) return (right = new SimpleNode<T>(data)); return right.addToTree(data); } }   public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2) { Stack<Node<T>> stack1 = new Stack<Node<T>>(); Stack<Node<T>> stack2 = new Stack<Node<T>>(); stack1.push(node1); stack2.push(node2); // NOT using short-circuit operator while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null)) if (!node1.getData().equals(node2.getData())) return false; // Return true if finished at same time return (node1 == null) && (node2 == null); }   private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack) { while (!stack.isEmpty()) { Node<T> node = stack.pop(); if (node.isLeaf()) return node; Node<T> rightNode = node.getRight(); if (rightNode != null) stack.push(rightNode); Node<T> leftNode = node.getLeft(); if (leftNode != null) stack.push(leftNode); } return null; }   public static void main(String[] args) { SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50))); SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null)))); SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56))))); System.out.print("Leaves for set 1: "); simpleWalk(headNode1); System.out.println(); System.out.print("Leaves for set 2: "); simpleWalk(headNode2); System.out.println(); System.out.print("Leaves for set 3: "); simpleWalk(headNode3); System.out.println(); System.out.println("areLeavesSame(1, 2)? " + areLeavesSame(headNode1, headNode2)); System.out.println("areLeavesSame(2, 3)? " + areLeavesSame(headNode2, headNode3)); }   public static void simpleWalk(Node<Integer> node) { if (node.isLeaf()) System.out.print(node.getData() + " "); else { Node<Integer> left = node.getLeft(); if (left != null) simpleWalk(left); Node<Integer> right = node.getRight(); if (right != null) simpleWalk(right); } } }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Mercury
Mercury
:- module sieve. :- interface. :- import_module io. :- pred main(io::di, io::uo) is det. :- implementation. :- import_module bool, array, int.   main(!IO) :- sieve(50, Sieve), dump_primes(2, size(Sieve), Sieve, !IO).   :- pred dump_primes(int, int, array(bool), io, io). :- mode dump_primes(in, in, array_di, di, uo) is det. dump_primes(N, Limit, !.A, !IO) :- ( if N < Limit then unsafe_lookup(!.A, N, Prime), ( Prime = yes, io.write_line(N, !IO)  ; Prime = no ), dump_primes(N + 1, Limit, !.A, !IO) else true ).   :- pred sieve(int, array(bool)). :- mode sieve(in, array_uo) is det. sieve(N, !:A) :- array.init(N, yes, !:A), sieve(2, N, !A).   :- pred sieve(int, int, array(bool), array(bool)). :- mode sieve(in, in, array_di, array_uo) is det. sieve(N, Limit, !A) :- ( if N < Limit then unsafe_lookup(!.A, N, Prime), ( Prime = yes, sift(N + N, N, Limit, !A), sieve(N + 1, Limit, !A)  ; Prime = no, sieve(N + 1, Limit, !A) ) else true ).   :- pred sift(int, int, int, array(bool), array(bool)). :- mode sift(in, in, in, array_di, array_uo) is det. sift(I, N, Limit, !A) :- ( if I < Limit then unsafe_set(I, no, !A), sift(I + N, N, Limit, !A) else true ).
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Lua
Lua
function valid(n,nuts) local k = n local i = 0 while k ~= 0 do if (nuts % n) ~= 1 then return false end k = k - 1 nuts = nuts - 1 - math.floor(nuts / n) end return nuts ~= 0 and (nuts % n == 0) end   for n=2, 9 do local x = 0 while not valid(n, x) do x = x + 1 end print(n..": "..x) end
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Elixir
Elixir
cities = [ [name: "Lagos", population: 21.0 ], [name: "Cairo", population: 15.2 ], [name: "Kinshasa-Brazzaville", population: 11.3 ], [name: "Greater Johannesburg", population: 7.55], [name: "Mogadishu", population: 5.85], [name: "Khartoum-Omdurman", population: 4.98], [name: "Dar Es Salaam", population: 4.7 ], [name: "Alexandria", population: 4.58], [name: "Abidjan", population: 4.4 ], [name: "Casablanca", population: 3.98] ]   IO.puts Enum.find_index(cities, fn city -> city[:name] == "Dar Es Salaam" end) IO.puts Enum.find(cities, fn city -> city[:population] < 5.0 end)[:name] IO.puts Enum.find(cities, fn city -> String.first(city[:name])=="A" end)[:population]
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Julia
Julia
  julia> using IntervalArithmetic   julia> n = 2.0 2.0   julia> @interval 2n/3 + 1 [2.33333, 2.33334]   julia> showall(ans) Interval(2.333333333333333, 2.3333333333333335)   julia> a = @interval(0.1, 0.3) [0.0999999, 0.300001]   julia> b = @interval(0.3, 0.6) [0.299999, 0.600001]   julia> a + b [0.399999, 0.900001]  
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Kotlin
Kotlin
// version 1.1.2   fun stepDown(d: Double) = Math.nextAfter(d, Double.NEGATIVE_INFINITY)   fun stepUp(d: Double) = Math.nextUp(d)   fun safeAdd(a: Double, b: Double) = stepDown(a + b).rangeTo(stepUp(a + b))   fun main(args: Array<String>) { val a = 1.2 val b = 0.03 println("($a + $b) is in the range ${safeAdd(a, b)}") }
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
import fenv, strutils   proc `++`(a, b: float): tuple[lower, upper: float] = let a {.volatile.} = a b {.volatile.} = b orig = fegetround() discard fesetround FE_DOWNWARD result.lower = a + b discard fesetround FE_UPWARD result.upper = a + b discard fesetround orig   proc ff(a: float): string = a.formatFloat(ffDefault, 17)   for x, y in [(1.0, 2.0), (0.1, 0.2), (1e100, 1e-100), (1e308, 1e308)].items: let (d,u) = x ++ y echo x.ff, " + ", y.ff, " =" echo " [", d.ff, ", ", u.ff, "]" echo " size ", (u - d).ff, "\n"
http://rosettacode.org/wiki/Ruth-Aaron_numbers
Ruth-Aaron numbers
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum. A Ruth–Aaron triple consists of three consecutive integers with the same properties. There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits. It is common to refer to each Ruth–Aaron group by the first number in it. Task Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors). Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors). Stretch Find and show the first Ruth-Aaron triple (factors). Find and show the first Ruth-Aaron triple (divisors). See also Wikipedia: Ruth–Aaron pair OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1 OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
#ALGOL_68
ALGOL 68
BEGIN # find Ruth-Aaron pairs - pairs of consecutive integers where the sum # # of the prime factors or divisors are equal # INT max number = 99 000 000; # max number we will consider # # construct a sieve of primes up to max number # [ 1 : max number ]BOOL prime; prime[ 1 ] := FALSE; prime[ 2 ] := TRUE; FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := TRUE OD; FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := FALSE OD; FOR i FROM 3 BY 2 TO ENTIER sqrt( UPB prime ) DO IF prime[ i ] THEN FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := FALSE OD FI OD; # construct the sums of prime divisors up to max number # [ 1 : max number ]INT ps; FOR n TO max number DO ps[ n ] := 0 OD; FOR n TO max number DO IF prime[ n ] THEN FOR j FROM n BY n TO max number DO ps[ j ] PLUSAB n OD FI OD; INT max count = 30; # first max count Ruth-Aaron (divisors) numbers # [ 1 : max count ]INT dra; INT count := 0; INT prev sum := 0; FOR n FROM 2 WHILE count < max count DO INT this sum = ps[ n ]; IF prev sum = this sum THEN # found another Ruth-Aaron number # count PLUSAB 1; IF count <= max count THEN dra[ count ] := n - 1 FI FI; prev sum := this sum OD; # first triple # INT dra3 := 0; INT pprev sum := ps[ 1 ]; prev sum := ps[ 2 ]; FOR n FROM 3 WHILE dra3 = 0 DO INT this sum = ps[ n ]; IF prev sum = this sum THEN IF pprev sum = this sum THEN # found a Ruth-Aaron triple # dra3 := n - 2 FI FI; pprev sum := prev sum; prev sum := this sum OD; # replace ps with the prime factor count # INT root max number = ENTIER sqrt( max number ); FOR n FROM 2 TO root max number DO IF prime[ n ] THEN INT p := n * n; WHILE p < root max number DO FOR j FROM p BY p TO max number DO ps[ j ] PLUSAB n OD; p TIMESAB n OD FI OD; # first max count Ruth-Aaron (factors) numbers # [ 1 : max count ]INT fra; prev sum := ps[ 1 ]; count := 0; FOR n FROM 2 WHILE count < 30 DO INT this sum = ps[ n ]; IF prev sum = this sum THEN # found another Ruth-Aaron number # count PLUSAB 1; fra[ count ] := n - 1 FI; prev sum := this sum OD; # first triple # prev sum := 0; count := 0; INT fra3 := 0; FOR n FROM 2 WHILE fra3 = 0 DO INT this sum = ps[ n ]; IF prev sum = this sum AND pprev sum = this sum THEN # found a Ruth-Aaron triple # fra3 := n - 2 FI; pprev sum := prev sum; prev sum := this sum OD; # show the numbers # print( ( "The first ", whole( max count, 0 ), " Ruth-Aaron numbers (factors):", newline ) ); FOR n TO max count DO print( ( whole( fra[ n ], - 6 ) ) ); IF n MOD 10 = 0 THEN print( ( newline ) ) FI OD; # divisors # print( ( "The first ", whole( max count, 0 ), " Ruth-Aaron numbers (divisors):", newline ) ); FOR n TO max count DO print( ( whole( dra[ n ], - 6 ) ) ); IF n MOD 10 = 0 THEN print( ( newline ) ) FI OD; # triples # print( ( newline, "First Ruth-Aaron triple (factors): ", whole( fra3, 0 ) ) ); print( ( newline, "First Ruth-Aaron triple (divisors): ", whole( dra3, 0 ) ) ) END
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Action.21
Action!
DEFINE PTR="CARD"   INT FUNC Search(PTR ARRAY texts INT count CHAR ARRAY text) INT i   FOR i=0 TO count-1 DO IF SCompare(texts(i),text)=0 THEN RETURN (i) FI OD RETURN (-1)   PROC Test(PTR ARRAY texts INT count CHAR ARRAY text) INT index   index=Search(texts,count,text) IF index=-1 THEN PrintF("""%S"" is not in haystack.%E",text) ELSE PrintF("""%S"" is on index %I in haystack.%E",text,index) FI RETURN   PROC Main() PTR ARRAY texts(7)   texts(0)="Monday" texts(1)="Tuesday" texts(2)="Wednesday" texts(3)="Thursday" texts(4)="Friday" texts(5)="Saturday" texts(6)="Sunday"   Test(texts,7,"Monday") Test(texts,7,"Sunday") Test(texts,7,"Thursday") Test(texts,7,"Weekend") RETURN
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <iterator> #include <locale> #include <vector> #include "prime_sieve.hpp"   const int limit1 = 1000000; const int limit2 = 10000000;   class prime_info { public: explicit prime_info(int max) : max_print(max) {} void add_prime(int prime); void print(std::ostream& os, const char* name) const; private: int max_print; int count1 = 0; int count2 = 0; std::vector<int> primes; };   void prime_info::add_prime(int prime) { ++count2; if (prime < limit1) ++count1; if (count2 <= max_print) primes.push_back(prime); }   void prime_info::print(std::ostream& os, const char* name) const { os << "First " << max_print << " " << name << " primes: "; std::copy(primes.begin(), primes.end(), std::ostream_iterator<int>(os, " ")); os << '\n'; os << "Number of " << name << " primes below " << limit1 << ": " << count1 << '\n'; os << "Number of " << name << " primes below " << limit2 << ": " << count2 << '\n'; }   int main() { // find the prime numbers up to limit2 prime_sieve sieve(limit2);   // write numbers with groups of digits separated according to the system default locale std::cout.imbue(std::locale(""));   // count and print safe/unsafe prime numbers prime_info safe_primes(35); prime_info unsafe_primes(40); for (int p = 2; p < limit2; ++p) { if (sieve.is_prime(p)) { if (sieve.is_prime((p - 1)/2)) safe_primes.add_prime(p); else unsafe_primes.add_prime(p); } } safe_primes.print(std::cout, "safe"); unsafe_primes.print(std::cout, "unsafe"); return 0; }
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#jq
jq
(t|flatten) == (s|flatten)
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#Julia
Julia
  using Lazy   """ Input a tree for display as a fringed structure. """ function fringe(tree) fringey(node::Pair) = [fringey(i) for i in node] fringey(leaf::Int) = leaf fringey(tree) end     """ equalsfringe() uses a reduction to a lazy 1D list via getleaflist() for its "equality" of fringes """ getleaflist(tree::Int) = [tree] getleaflist(tree::Pair) = vcat(getleaflist(seq(tree[1])), getleaflist(seq(tree[2]))) getleaflist(tree::Lazy.LazyList) = vcat(getleaflist(tree[1]), getleaflist(tree[2])) getleaflist(tree::Void) = [] equalsfringe(t1, t2) = (getleaflist(t1) == getleaflist(t2))     a = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8 b = 1 => (( 2 => 3 ) => (4 => (5 => ((6 => 7) => 8)))) c = (((1 => 2) => 3) => 4) => 5 => 6 => 7 => 8   x = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8 => 9 y = 0 => 2 => 3 => 4 => 5 => 6 => 7 => 8 z = 1 => 2 => (4 => 3) => 5 => 6 => 7 => 8   prettyprint(s) = println(replace("$s", r"\{Any,1\}|Any|Array\{T,1\}\swhere\sT|Array|", "")) prettyprint(fringe(a)) prettyprint(fringe(b)) prettyprint(fringe(c)) prettyprint(fringe(x)) prettyprint(fringe(y)) prettyprint(fringe(z))   prettyprint(getleaflist(a)) prettyprint(getleaflist(b)) prettyprint(getleaflist(c))   println(equalsfringe(a, a)) println(equalsfringe(a, b)) println(equalsfringe(a, c)) println(equalsfringe(b, c)) println(equalsfringe(a, x) == false) println(equalsfringe(a, y) == false) println(equalsfringe(a, z) == false)  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Microsoft_Small_Basic
Microsoft Small Basic
  TextWindow.Write("Enter number to search to: ") limit = TextWindow.ReadNumber() For n = 2 To limit flags[n] = 0 EndFor For n = 2 To math.SquareRoot(limit) If flags[n] = 0 Then For K = n * n To limit Step n flags[K] = 1 EndFor EndIf EndFor ' Display the primes If limit >= 2 Then TextWindow.Write(2) For n = 3 To limit If flags[n] = 0 Then TextWindow.Write(", " + n) EndIf EndFor TextWindow.WriteLine("") EndIf  
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[SequenceOk] SequenceOk[n_, k_] := Module[{m = n, q, r, valid = True}, Do[ {q, r} = QuotientRemainder[m, k]; If[r != 1, valid = False; Break[]; ]; m -= q + 1 , {k} ]; If[Mod[m, k] != 0, valid = False ]; valid ] i = 1; While[! SequenceOk[i, 5], i++] i   i = 1; While[! SequenceOk[i, 6], i++] i
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Modula-2
Modula-2
MODULE Coconuts; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   CONST MAX_SAILORS = 9;   PROCEDURE Scenario(coconuts,ns : INTEGER); VAR buf : ARRAY[0..63] OF CHAR; hidden : ARRAY[0..MAX_SAILORS-1] OF INTEGER; nc,s,t : INTEGER; BEGIN IF ns>MAX_SAILORS THEN RETURN END;   coconuts := (coconuts DIV ns) * ns + 1; LOOP nc := coconuts; FOR s:=1 TO ns DO IF nc MOD ns = 1 THEN hidden[s-1] := nc DIV ns; nc := nc - hidden[s-1] - 1; IF (s=ns) AND (nc MOD ns = 0) THEN FormatString("%i sailors require a minimum of %i coconuts\n", buf, ns, coconuts); WriteString(buf);   FOR t:=1 TO ns DO FormatString("\tSailor %i hides %i\n", buf, t, hidden[t-1]); WriteString(buf) END;   FormatString("\tThe monkey gets %i\n", buf, ns); WriteString(buf); FormatString("\tFinally, each sailor takes %i\n", buf, nc DIV ns); WriteString(buf); RETURN END ELSE BREAK END END; INC(coconuts,ns) END END Scenario;   VAR ns : INTEGER; BEGIN FOR ns:=2 TO MAX_SAILORS DO Scenario(11,ns); END;   ReadChar END Coconuts.
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Factor
Factor
USING: accessors io kernel math prettyprint sequences ; IN: rosetta-code.search-list   TUPLE: city name pop ;   CONSTANT: data { T{ city f "Lagos" 21.0 } T{ city f "Cairo" 15.2 } T{ city f "Kinshasa-Brazzaville" 11.3 } T{ city f "Greater Johannesburg" 7.55 } T{ city f "Mogadishu" 5.85 } T{ city f "Khartoum-Omdurman" 4.98 } T{ city f "Dar Es Salaam" 4.7 } T{ city f "Alexandria" 4.58 } T{ city f "Abidjan" 4.4 } T{ city f "Casablanca" 3.98 } }   ! Print the index of the first city named Dar Es Salaam. data [ name>> "Dar Es Salaam" = ] find drop .   ! Print the name of the first city with under 5 million people. data [ pop>> 5 < ] find nip name>> print   ! Print the population of the first city starting with 'A'. data [ name>> first CHAR: A = ] find nip pop>> .
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Nim
Nim
import fenv, strutils   proc `++`(a, b: float): tuple[lower, upper: float] = let a {.volatile.} = a b {.volatile.} = b orig = fegetround() discard fesetround FE_DOWNWARD result.lower = a + b discard fesetround FE_UPWARD result.upper = a + b discard fesetround orig   proc ff(a: float): string = a.formatFloat(ffDefault, 17)   for x, y in [(1.0, 2.0), (0.1, 0.2), (1e100, 1e-100), (1e308, 1e308)].items: let (d,u) = x ++ y echo x.ff, " + ", y.ff, " =" echo " [", d.ff, ", ", u.ff, "]" echo " size ", (u - d).ff, "\n"
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Perl
Perl
use strict; use warnings; use Data::IEEE754::Tools <nextUp nextDown>;   sub safe_add { my($a,$b) = @_; my $c = $a + $b; return $c, nextDown($c), nextUp($c) }   printf "%.17f (%.17f, %.17f)\n", safe_add (1/9,1/7);
http://rosettacode.org/wiki/Ruth-Aaron_numbers
Ruth-Aaron numbers
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum. A Ruth–Aaron triple consists of three consecutive integers with the same properties. There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits. It is common to refer to each Ruth–Aaron group by the first number in it. Task Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors). Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors). Stretch Find and show the first Ruth-Aaron triple (factors). Find and show the first Ruth-Aaron triple (divisors). See also Wikipedia: Ruth–Aaron pair OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1 OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
#C.2B.2B
C++
#include <iomanip> #include <iostream>   int prime_factor_sum(int n) { int sum = 0; for (; (n & 1) == 0; n >>= 1) sum += 2; for (int p = 3, sq = 9; sq <= n; p += 2) { for (; n % p == 0; n /= p) sum += p; sq += (p + 1) << 2; } if (n > 1) sum += n; return sum; }   int prime_divisor_sum(int n) { int sum = 0; if ((n & 1) == 0) { sum += 2; n >>= 1; while ((n & 1) == 0) n >>= 1; } for (int p = 3, sq = 9; sq <= n; p += 2) { if (n % p == 0) { sum += p; n /= p; while (n % p == 0) n /= p; } sq += (p + 1) << 2; } if (n > 1) sum += n; return sum; }   int main() { const int limit = 30; int dsum1 = 0, fsum1 = 0, dsum2 = 0, fsum2 = 0;   std::cout << "First " << limit << " Ruth-Aaron numbers (factors):\n"; for (int n = 2, count = 0; count < limit; ++n) { fsum2 = prime_factor_sum(n); if (fsum1 == fsum2) { ++count; std::cout << std::setw(5) << n - 1 << (count % 10 == 0 ? '\n' : ' '); } fsum1 = fsum2; }   std::cout << "\nFirst " << limit << " Ruth-Aaron numbers (divisors):\n"; for (int n = 2, count = 0; count < limit; ++n) { dsum2 = prime_divisor_sum(n); if (dsum1 == dsum2) { ++count; std::cout << std::setw(5) << n - 1 << (count % 10 == 0 ? '\n' : ' '); } dsum1 = dsum2; }   dsum1 = 0, fsum1 = 0, dsum2 = 0, fsum2 = 0; for (int n = 2;; ++n) { int fsum3 = prime_factor_sum(n); if (fsum1 == fsum2 && fsum2 == fsum3) { std::cout << "\nFirst Ruth-Aaron triple (factors): " << n - 2 << '\n'; break; } fsum1 = fsum2; fsum2 = fsum3; } for (int n = 2;; ++n) { int dsum3 = prime_divisor_sum(n); if (dsum1 == dsum2 && dsum2 == dsum3) { std::cout << "\nFirst Ruth-Aaron triple (divisors): " << n - 2 << '\n'; break; } dsum1 = dsum2; dsum2 = dsum3; } }
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#ActionScript
ActionScript
var list:Vector.<String> = Vector.<String>(["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]); function lowIndex(listToSearch:Vector.<String>, searchString:String):int { var index:int = listToSearch.indexOf(searchString); if(index == -1) throw new Error("String not found: " + searchString); return index; }   function highIndex(listToSearch:Vector.<String>, searchString:String):int { var index:int = listToSearch.lastIndexOf(searchString); if(index == -1) throw new Error("String not found: " + searchString); return index; }
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#CLU
CLU
isqrt = proc (s: int) returns (int) x0: int := s/2 if x0=0 then return(s) end x1: int := (x0 + s/x0)/2 while x1 < x0 do x0 := x1 x1 := (x0 + s/x0)/2 end return(x0) end isqrt   sieve = proc (n: int) returns (array[bool]) prime: array[bool] := array[bool]$fill(0,n+1,true) prime[0] := false prime[1] := false for p: int in int$from_to(2, isqrt(n)) do if prime[p] then for c: int in int$from_to_by(p*p,n,p) do prime[c] := false end end end return(prime) end sieve   start_up = proc () primeinfo = record [ name: string, ps: array[int], maxps, n_1e6, n_1e7: int ]   po: stream := stream$primary_output() prime: array[bool] := sieve(10000000)   safe: primeinfo := primeinfo${ name: "safe", ps: array[int]$[], maxps: 35, n_1e6: 0, n_1e7: 0 }   unsafe: primeinfo := primeinfo${ name: "unsafe", ps: array[int]$[], maxps: 40, n_1e6: 0, n_1e7: 0 }   for p: int in int$from_to(2, 10000000) do if ~prime[p] then continue end ir: primeinfo if prime[(p-1)/2] then ir := safe else ir := unsafe end   if array[int]$size(ir.ps) < ir.maxps then array[int]$addh(ir.ps,p) end if p<1000000 then ir.n_1e6 := ir.n_1e6 + 1 end if p<10000000 then ir.n_1e7 := ir.n_1e7 + 1 end end   for ir: primeinfo in array[primeinfo]$elements( array[primeinfo]$[safe, unsafe]) do stream$putl(po, "First " || int$unparse(ir.maxps) || " " || ir.name || " primes:") for i: int in array[int]$elements(ir.ps) do stream$puts(po, int$unparse(i) || " ") end stream$putl(po, "\nThere are " || int$unparse(ir.n_1e6) || " " || ir.name || " primes < 1,000,000.") stream$putl(po, "There are " || int$unparse(ir.n_1e7) || " " || ir.name || " primes < 1,000,000.\n") end end start_up
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#D
D
import std.stdio;   immutable PRIMES = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331 ];   bool isPrime(const int n) { if (n < 2) { return false; }   foreach (p; PRIMES) { if (n == p) { return true; } if (n % p == 0) { return false; } if (n < p * p) { return true; } }   int i = (PRIMES[$ - 1] / 6) * 6 - 1; while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; }   return true; }   void main() { int beg = 2; int end = 1_000_000; int count = 0;   // safe primes ///////////////////////////////////////////   writeln("First 35 safe primes:"); foreach (i; beg..end) { if (isPrime(i) && isPrime((i - 1) / 2)) { if (count < 35) { write(i, ' '); } count++; } } writefln("\nThere are %5d safe primes below %8d", count, end);   beg = end; end *= 10; foreach (i; beg..end) { if (isPrime(i) && isPrime((i - 1) / 2)) { count++; } } writefln("There are %5d safe primes below %8d", count, end);   // unsafe primes ///////////////////////////////////////////   beg = 2; end = 1_000_000; count = 0; writeln("\nFirst 40 unsafe primes:"); foreach (i; beg..end) { if (isPrime(i) && !isPrime((i - 1) / 2)) { if (count < 40) { write(i, ' '); } count++; } } writefln("\nThere are %6d unsafe primes below %9d", count, end);   beg = end; end *= 10; foreach (i; beg..end) { if (isPrime(i) && !isPrime((i - 1) / 2)) { count++; } } writefln("There are %6d unsafe primes below %9d", count, end); }
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#Lua
Lua
local type, insert, remove = type, table.insert, table.remove   None = {} -- a unique object for a truncated branch (i.e. empty subtree) function isbranch(node) return type(node) == 'table' and #node == 2 end function left(node) return node[1] end function right(node) return node[2] end   function fringeiter(tree) local agenda = {tree} local function push(item) insert(agenda, item) end local function pop() return remove(agenda) end return function() while #agenda > 0 do node = pop() if isbranch(node) then push(right(node)) push(left(node)) elseif node == None then -- continue else return node end end end end   function same_fringe(atree, btree) local anext = fringeiter(atree or None) local bnext = fringeiter(btree or None) local pos = 0 repeat local aitem, bitem = anext(), bnext() pos = pos + 1 if aitem ~= bitem then return false, string.format("at position %d, %s ~= %s", pos, aitem, bitem) end until not aitem return true end   t1 = {1, {2, {3, {4, {5, None}}}}} t2 = {{1,2}, {{3, 4}, 5}} t3 = {{{1,2}, 3}, 4}   function compare_fringe(label, ta, tb) local equal, nonmatch = same_fringe(ta, tb) io.write(label .. ": ") if equal then print("same fringe") else print(nonmatch) end end   compare_fringe("(t1, t2)", t1, t2) compare_fringe("(t1, t3)", t1, t3)  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Modula-2
Modula-2
MODULE Erato; FROM InOut IMPORT WriteCard, WriteLn; FROM MathLib IMPORT sqrt;   CONST Max = 100;   VAR prime: ARRAY [2..Max] OF BOOLEAN; i: CARDINAL;   PROCEDURE Sieve; VAR i, j, sqmax: CARDINAL; BEGIN sqmax := TRUNC(sqrt(FLOAT(Max)));   FOR i := 2 TO Max DO prime[i] := TRUE; END; FOR i := 2 TO sqmax DO IF prime[i] THEN j := i * 2; (* alas, the BY clause in a FOR loop must be a constant *) WHILE j <= Max DO prime[j] := FALSE; j := j + i; END; END; END; END Sieve;   BEGIN Sieve; FOR i := 2 TO Max DO IF prime[i] THEN WriteCard(i,5); WriteLn; END; END; END Erato.
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Nim
Nim
import strformat   var coconuts = 11   for ns in 2..9: var hidden = newSeq[int](ns) coconuts = (coconuts div ns) * ns + 1 block Search: while true: var nc = coconuts for sailor in 1..ns: if nc mod ns == 1: hidden[sailor-1] = nc div ns dec nc, hidden[sailor-1] + 1 if sailor == ns and nc mod ns == 0: echo &"{ns} sailors require a minimum of {coconuts} coconuts." for t in 1..ns: echo &"\tSailor {t} hides {hidden[t-1]}." echo &"\tThe monkey gets {ns}." echo &"\tFinally, each sailor takes {nc div ns}.\n" break Search # Done. Continue with more sailors or exit. else: break # Failed. Continue search with more coconuts. inc coconuts, ns
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Objeck
Objeck
  class Program { function : Total(n : Int, nuts : Int) ~ Int { k := 0; for(nuts *= n; k < n; k++;) { if(nuts % (n-1) <> 0) { return 0; }; nuts += nuts / (n-1) + 1; };   return nuts; }   function : Main(args : String[]) ~ Nil { for(n := 2; n < 10; n++;) { x := 0; t := 0; do { x++; t := Total(n, x); } while(t = 0); "{$n}: {$t}, {$x}"->PrintLine(); }; } }  
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Fortran
Fortran
MODULE SEMPERNOVIS !Keep it together. TYPE CITYSTAT !Define a compound data type. CHARACTER*28 NAME !Long enough? REAL POPULATION !Accurate enough. END TYPE CITYSTAT !Just two parts, but different types. TYPE(CITYSTAT) CITY(10) !Righto, I'll have some. DATA CITY/ !Supply the example's data. 1 CITYSTAT("Lagos", 21.0 ), 2 CITYSTAT("Cairo", 15.2 ), 3 CITYSTAT("Kinshasa-Brazzaville",11.3 ), 4 CITYSTAT("Greater Johannesburg", 7.55), 5 CITYSTAT("Mogadishu", 5.85), 6 CITYSTAT("Khartoum-Omdurman", 4.98), 7 CITYSTAT("Dar Es Salaam", 4.7 ), 8 CITYSTAT("Alexandria", 4.58), 9 CITYSTAT("Abidjan", 4.4 ), o CITYSTAT("Casablanca", 3.98)/ CONTAINS INTEGER FUNCTION FIRSTMATCH(TEXT,TARGET) !First matching. CHARACTER*(*) TEXT(:) !An array of texts. CHARACTER*(*) TARGET !The text to look for. DO FIRSTMATCH = 1,UBOUND(TEXT,DIM = 1) !Scan the array from the start. IF (TEXT(FIRSTMATCH) .EQ. TARGET) RETURN !An exact match? Ignoring trailing spaces. END DO !Try the next. FIRSTMATCH = 0 !No match. Oh dear. END FUNCTION FIRSTMATCH   INTEGER FUNCTION FIRSTLESS(VAL,TARGET) !First matching. REAL VAL(:) !An array of values. REAL TARGET !The value to look for. DO FIRSTLESS = 1,UBOUND(VAL,DIM = 1) !Step through the array from the start. IF (VAL(FIRSTLESS) .LT. TARGET) RETURN !Suitable? END DO !Try the next. FIRSTLESS = 0 !No match. Oh dear. END FUNCTION FIRSTLESS END MODULE SEMPERNOVIS   PROGRAM POKE USE SEMPERNOVIS !Ex Africa, ... CHARACTER*(*) BLAH !Save on some typing. PARAMETER (BLAH = "The first city in the list whose ") !But also, for layout.   WRITE (6,1) BLAH,FIRSTMATCH(CITY.NAME,"Dar Es Salaam") - 1 !My array starts with one. 1 FORMAT (A,"name is Dar Es Salaam, counting with zero, is #",I0)   WRITE (6,2) BLAH,CITY(FIRSTLESS(CITY.POPULATION,5.0)).NAME 2 FORMAT (A,"population is less than 5 is ",A)   WRITE (6,3) BLAH,CITY(FIRSTMATCH(CITY.NAME(1:1),"A")).POPULATION 3 FORMAT (A,"whose name starts with A has population",F5.2) END
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Phix
Phix
include builtins\VM\pFPU.e -- :%down53 etc function safe_add(atom a, atom b) atom low,high -- NB: be sure to restore the usual/default rounding! #ilASM{ [32] lea esi,[a] call :%pLoadFlt lea esi,[b] call :%pLoadFlt fld st0 call :%down53 fadd st0,st2 lea edi,[low] call :%pStoreFlt call :%up53 faddp lea edi,[high] call :%pStoreFlt call :%near53 -- usual/default [64] lea rsi,[a] call :%pLoadFlt lea rsi,[b] call :%pLoadFlt fld st0 call :%down64 fadd st0,st2 lea rdi,[low] call :%pStoreFlt call :%up64 faddp lea rdi,[high] call :%pStoreFlt call :%near64 -- usual/default [] } return {low,high} end function constant nums = {{1, 2}, {0.1, 0.2}, {1e100, 1e-100}, {1e308, 1e308}} for i=1 to length(nums) do atom {a,b} = nums[i] atom {low,high} = safe_add(a,b) printf(1,"%.16g + %.16g =\n", {a, b}); printf(1," [%.16g, %.16g]\n", {low, high}); printf(1," size %.16g\n\n", high - low); end for
http://rosettacode.org/wiki/Ruth-Aaron_numbers
Ruth-Aaron numbers
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum. A Ruth–Aaron triple consists of three consecutive integers with the same properties. There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits. It is common to refer to each Ruth–Aaron group by the first number in it. Task Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors). Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors). Stretch Find and show the first Ruth-Aaron triple (factors). Find and show the first Ruth-Aaron triple (divisors). See also Wikipedia: Ruth–Aaron pair OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1 OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
#Factor
Factor
USING: assocs.extras grouping io kernel lists lists.lazy math math.primes.factors prettyprint ranges sequences ;   : pair-same? ( ... n quot: ( ... m -- ... n ) -- ... ? ) [ dup 1 + ] dip same? ; inline   : RA-f? ( n -- ? ) [ factors sum ] pair-same? ; : RA-d? ( n -- ? ) [ group-factors sum-keys ] pair-same? ; : filter-naturals ( quot -- list ) 1 lfrom swap lfilter ; inline : RA-f ( -- list ) [ RA-f? ] filter-naturals ; : RA-d ( -- list ) [ RA-d? ] filter-naturals ;   : list. ( list -- ) 30 swap ltake list>array 10 group simple-table. ;   "First 30 Ruth-Aaron numbers (factors):" print RA-f list. nl   "First 30 Ruth-Aaron numbers (divisors):" print RA-d list.
http://rosettacode.org/wiki/Ruth-Aaron_numbers
Ruth-Aaron numbers
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum. A Ruth–Aaron triple consists of three consecutive integers with the same properties. There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits. It is common to refer to each Ruth–Aaron group by the first number in it. Task Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors). Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors). Stretch Find and show the first Ruth-Aaron triple (factors). Find and show the first Ruth-Aaron triple (divisors). See also Wikipedia: Ruth–Aaron pair OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1 OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
#Go
Go
package main   import ( "fmt" "rcu" )   func prune(a []int) []int { prev := a[0] b := []int{prev} for i := 1; i < len(a); i++ { if a[i] != prev { b = append(b, a[i]) prev = a[i] } } return b }   func main() { var resF, resD, resT, factors1 []int factors2 := []int{2} factors3 := []int{3} var sum1, sum2, sum3 int = 0, 2, 3 var countF, countD, countT int for n := 2; countT < 1 || countD < 30 || countF < 30; n++ { factors1 = factors2 factors2 = factors3 factors3 = rcu.PrimeFactors(n + 2) sum1 = sum2 sum2 = sum3 sum3 = rcu.SumInts(factors3) if countF < 30 && sum1 == sum2 { resF = append(resF, n) countF++ } if sum1 == sum2 && sum2 == sum3 { resT = append(resT, n) countT++ } if countD < 30 { factors4 := make([]int, len(factors1)) copy(factors4, factors1) factors5 := make([]int, len(factors2)) copy(factors5, factors2) factors4 = prune(factors4) factors5 = prune(factors5) if rcu.SumInts(factors4) == rcu.SumInts(factors5) { resD = append(resD, n) countD++ } } } fmt.Println("First 30 Ruth-Aaron numbers (factors):") fmt.Println(resF) fmt.Println("\nFirst 30 Ruth-Aaron numbers (divisors):") fmt.Println(resD) fmt.Println("\nFirst Ruth-Aaron triple (factors):") fmt.Println(resT[0])   resT = resT[:0] factors1 = factors1[:0] factors2 = factors2[:1] factors2[0] = 2 factors3 = factors3[:1] factors3[0] = 3 countT = 0 for n := 2; countT < 1; n++ { factors1 = factors2 factors2 = factors3 factors3 = prune(rcu.PrimeFactors(n + 2)) sum1 = sum2 sum2 = sum3 sum3 = rcu.SumInts(factors3) if sum1 == sum2 && sum2 == sum3 { resT = append(resT, n) countT++ } } fmt.Println("\nFirst Ruth-Aaron triple (divisors):") fmt.Println(resT[0]) }
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Ada
Ada
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO;   procedure Test_List_Index is Not_In : exception;   type List is array (Positive range <>) of Unbounded_String;   function Index (Haystack : List; Needle : String) return Positive is begin for Index in Haystack'Range loop if Haystack (Index) = Needle then return Index; end if; end loop; raise Not_In; end Index;   -- Functions to create lists function "+" (X, Y : String) return List is begin return (1 => To_Unbounded_String (X), 2 => To_Unbounded_String (Y)); end "+";   function "+" (X : List; Y : String) return List is begin return X & (1 => To_Unbounded_String (Y)); end "+";   Haystack : List := "Zig"+"Zag"+"Wally"+"Ronald"+"Bush"+"Krusty"+"Charlie"+"Bush"+"Bozo";   procedure Check (Needle : String) is begin Put (Needle); Put_Line ("at" & Positive'Image (Index (Haystack, Needle))); exception when Not_In => Put_Line (" is not in"); end Check; begin Check ("Washington"); Check ("Bush"); end Test_List_Index;
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#6502_Assembly
6502 Assembly
;Init Routine *=$0801 db $0E,$08,$0A,$00,$9E,$20,$28,$32,$30,$36,$34,$29,$00,$00,$00 *=$0810 ;Start at $0810     LDA #$A9 ;opcode for LDA immediate STA smc_test   LDA #'A' STA smc_test+1   lda #$20 ;opcode for JSR STA smc_test+2   lda #<CHROUT STA smc_test+3   lda #>CHROUT STA smc_test+4     smc_test: nop ;gets overwritten with LDA nop ;gets overwritten with #$41 nop ;gets overwritten with JSR nop ;gets overwritten with <CHROUT nop ;gets overwritten with >CHROUT     rts ;return to basic
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#F.23
F#
  pCache |> Seq.filter(fun n->isPrime((n-1)/2)) |> Seq.take 35 |> Seq.iter (printf "%d ")  
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#Nim
Nim
import random, sequtils, strutils   type Node = ref object value: int left, right: Node     proc add(tree: var Node; value: int) = ## Add a node to a tree (or subtree), insuring values are in increasing order. if tree.isNil: tree = Node(value: value) elif value <= tree.value: tree.left.add value else: tree.right.add value     proc newTree(list: varargs[int]): Node = ## Create a new tree with the given nodes. for value in list: result.add value     proc `$`(tree: Node): string = # Display a tree. if tree.isNil: return result = '(' & $tree.left & $tree.value & $tree.right & ')'     iterator nodes(tree: Node): Node = ## Yield the successive leaves of a tree. ## Iterators cannot be recursive, so we have to manage a stack. ## Note: with Nim 1.4 a bug prevents to use a closure iterator, ## so we use an inline iterator which is not optimal here.   type Direction {.pure.} = enum Up, Down Item = (Node, Direction)   var stack: seq[Item] stack.add (nil, Down) # Sentinel to avoid checking for empty stack.   var node = tree var dir = Down   while not node.isNil: if dir == Down and not node.left.isNil: # Process left subtree. stack.add (node, Up) node = node.left else: yield node # Process right subtree of pop an element form stack. (node, dir) = if node.right.isNil: stack.pop() else: (node.right, Down)     proc haveSameFringe(tree1, tree2: Node): bool = ## Return true if the trees have the same fringe. ## Check is done node by node and terminates as soon as ## a difference is encountered. let iter1 = iterator: Node = (for node in tree1.nodes: yield node) let iter2 = iterator: Node = (for node in tree2.nodes: yield node) while true: let node1 = iter1() let node2 = iter2() if iter1.finished and iter2.finished: return true # Both terminates at same round. if iter1.finished or iter2.finished: return false # One terminates before the other. if node1.value != node2.value: return false     when isMainModule: randomize() var values = [1, 2, 3, 4, 5, 6, 7, 8, 9]   values.shuffle() let tree1 = newTree(values) echo "First tree: ", tree1   values.shuffle() let tree2 = newTree(values) echo "Second tree: ", tree2   let s = if haveSameFringe(tree1, tree2): "have " else: "don’t have " echo "The trees ", s, "same fringe: ", toSeq(tree1.nodes()).mapIt(it.value).join(", ")
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Modula-3
Modula-3
MODULE Eratosthenes EXPORTS Main;   IMPORT IO;   FROM Math IMPORT sqrt;   CONST LastNum = 1000; ListPrimes = TRUE;   VAR a: ARRAY[2..LastNum] OF BOOLEAN;   VAR n := LastNum - 2 + 1;   BEGIN   (* set up *) FOR i := FIRST(a) TO LAST(a) DO a[i] := TRUE; END;   (* declare a variable local to a block *) VAR b := FLOOR(sqrt(FLOAT(LastNum, LONGREAL)));   (* the block must follow immediately *) BEGIN   (* print primes and mark out composites up to sqrt(LastNum) *) FOR i := FIRST(a) TO b DO IF a[i] THEN IF ListPrimes THEN IO.PutInt(i); IO.Put(" "); END; FOR j := i*i TO LAST(a) BY i DO IF a[j] THEN a[j] := FALSE; DEC(n); END; END; END; END;   (* print remaining primes *) IF ListPrimes THEN FOR i := b + 1 TO LAST(a) DO IF a[i] THEN IO.PutInt(i); IO.Put(" "); END; END; END;   END;   (* report *) IO.Put("There are "); IO.PutInt(n); IO.Put(" primes from 2 to "); IO.PutInt(LastNum); IO.PutChar('\n');   END Eratosthenes.
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Perl
Perl
use bigint;   for $sailors (1..15) { check( $sailors, coconuts( 0+$sailors ) ) }   sub is_valid { my($sailors, $nuts) = @_; return 0, 0 if $sailors == 1 and $nuts == 1; my @shares; for (1..$sailors) { return () unless ($nuts % $sailors) == 1; push @shares, int ($nuts-1)/$sailors; $nuts -= (1 + int $nuts/$sailors); } push @shares, int $nuts/$sailors; return @shares if !($nuts % $sailors); }   sub check { my($sailors, $coconuts) = @_; my @suffix = ('th', 'st', 'nd', 'rd', ('th') x 6, ('th') x 10); my @piles = is_valid($sailors, $coconuts); if (@piles) { print "\nSailors $sailors: Coconuts $coconuts:\n"; for my $k (0..-1 + $#piles) { print $k+1 . $suffix[$k+1] . " takes " . $piles[$k] . ", gives 1 to the monkey.\n" } print "The next morning, each sailor takes " . $piles[-1] . "\nwith none left over for the monkey.\n"; return 1 } return 0 }   sub coconuts { my($sailors) = @_; if ($sailors % 2 == 0 ) { ($sailors ** $sailors - 1) * ($sailors - 1) } else { $sailors ** $sailors - $sailors + 1 } }
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Go
Go
package main   import ( "fmt" "strings" )   type element struct { name string population float64 }   var list = []element{ {"Lagos", 21}, {"Cairo", 15.2}, {"Kinshasa-Brazzaville", 11.3}, {"Greater Johannesburg", 7.55}, {"Mogadishu", 5.85}, {"Khartoum-Omdurman", 4.98}, {"Dar Es Salaam", 4.7}, {"Alexandria", 4.58}, {"Abidjan", 4.4}, {"Casablanca", 3.98}, }   func find(cond func(*element) bool) int { for i := range list { if cond(&list[i]) { return i } } return -1 }   func main() { fmt.Println(find(func(e *element) bool { return e.name == "Dar Es Salaam" }))   i := find(func(e *element) bool { return e.population < 5 }) if i < 0 { fmt.Println("*** not found ***") } else { fmt.Println(list[i].name) }   i = find(func(e *element) bool { return strings.HasPrefix(e.name, "A") }) if i < 0 { fmt.Println("*** not found ***") } else { fmt.Println(list[i].population) } }
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#PicoLisp
PicoLisp
>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 0.9999999999999999 >>> from math import fsum >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 1.0
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Python
Python
>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 0.9999999999999999 >>> from math import fsum >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 1.0
http://rosettacode.org/wiki/Ruth-Aaron_numbers
Ruth-Aaron numbers
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum. A Ruth–Aaron triple consists of three consecutive integers with the same properties. There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits. It is common to refer to each Ruth–Aaron group by the first number in it. Task Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors). Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors). Stretch Find and show the first Ruth-Aaron triple (factors). Find and show the first Ruth-Aaron triple (divisors). See also Wikipedia: Ruth–Aaron pair OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1 OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
#Haskell
Haskell
import qualified Data.Set as S import Data.List.Split ( chunksOf )   divisors :: Int -> [Int] divisors n = [d | d <- [2 .. n] , mod n d == 0]   --for obvious theoretical reasons the smallest divisor of a number bare 1 --must be prime primeFactors :: Int -> [Int] primeFactors n = snd $ until ( (== 1) . fst ) step (n , [] ) where step :: (Int , [Int] ) -> (Int , [Int] ) step (n , li) = ( div n h , li ++ [h] ) where h :: Int h = head $ divisors n   primeDivisors :: Int -> [Int] primeDivisors n = S.toList $ S.fromList $ primeFactors n   solution :: (Int -> [Int] ) -> [Int] solution f = snd $ until ( (== 30 ) . length . snd ) step ([2 , 3] , [] ) where step :: ([Int] , [Int] ) -> ([Int] , [Int]) step ( neighbours , ranums ) = ( map ( + 1 ) neighbours , if (sum $ f $ head neighbours ) == (sum $ f $ last neighbours) then ranums ++ [ head neighbours ] else ranums )   formatNumber :: Int -> String -> String formatNumber width num |width > l = replicate ( width -l ) ' ' ++ num |width == l = num |width < l = num where l = length num   main :: IO ( ) main = do let ruth_aaron_pairs = solution primeFactors maxlen = length $ show $ last ruth_aaron_pairs numberlines = chunksOf 8 $ map show ruth_aaron_pairs ruth_aaron_divisors = solution primeDivisors maxlen2 = length $ show $ last ruth_aaron_divisors numberlines2 = chunksOf 8 $ map show ruth_aaron_divisors putStrLn "First 30 Ruth-Aaaron numbers ( factors ) :" mapM_ (\nlin -> putStrLn $ foldl1 ( ++ ) $ map (\st -> formatNumber (maxlen + 2) st ) nlin ) numberlines putStrLn " " putStrLn "First 30 Ruth-Aaron numbers( divisors ):" mapM_ (\nlin -> putStrLn $ foldl1 ( ++ ) $ map (\st -> formatNumber (maxlen2 + 2) st ) nlin ) numberlines2
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Aime
Aime
void search(list l, text s) { integer i;   i = 0; while (i < ~l) { if (l[i] == s) { break; } i += 1; }   o_(s, " is ", i == ~l ? "not in the haystack" : "at " + itoa(i), "\n"); }   integer main(void) { list l;   l = l_effect("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"); __ucall(search, 1, 1, l, "Bush", "Washington", "Zag");   return 0; }
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#ALGOL_68
ALGOL 68
print(evaluate("4.0*arctan(1.0)"))
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Arturo
Arturo
a: {print ["The result is:" 2+3]} do a   userCode: input "Give me some code: " do userCode
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#AutoHotkey
AutoHotkey
; requires AutoHotkey_H or AutoHotkey.dll msgbox % eval("3 + 4") msgbox % eval("4 + 4") return     eval(expression) { global script script = ( expression(){ return %expression% } ) renameFunction("expression", "") ; remove any previous expressions gosub load ; cannot use addScript inside a function yet exp := "expression" return %exp%() }   load: DllCall(A_AhkPath "\addScript","Str",script,"Uchar",0,"Cdecl UInt") return   renameFunction(funcName, newname){ static x%newname% := newname ; store newname in a static variable so its memory is not freed strput(newname, &x%newname%, strlen(newname) + 1) if fnp := FindFunc(funcName) numput(&x%newname%, fnp+0, 0, "uint") }
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Factor
Factor
USING: fry interpolate kernel literals math math.primes sequences tools.memory.private ; IN: rosetta-code.safe-primes   CONSTANT: primes $[ 10,000,000 primes-upto ]   : safe/unsafe ( -- safe unsafe ) primes [ 1 - 2/ prime? ] partition ;   : count< ( seq n -- str ) '[ _ < ] count commas ;   : seq>commas ( seq -- str ) [ commas ] map " " join ;   : stats ( seq n -- head count1 count2 ) '[ _ head seq>commas ] [ 1e6 count< ] [ 1e7 count< ] tri ;   safe/unsafe [ 35 ] [ 40 ] bi* [ stats ] 2bi@   [I First 35 safe primes: ${5} Safe prime count below 1,000,000: ${4} Safe prime count below 10,000,000: ${3}   First 40 unsafe primes: ${2} Unsafe prime count below 1,000,000: ${1} Unsafe prime count below 10,000,000: ${} I]
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#FreeBASIC
FreeBASIC
' version 19-01-2019 ' compile with: fbc -s console   Const As UInteger max = 10000000 Dim As UInteger i, j, sc1, usc1, sc2, usc2 Dim As String safeprimes, unsafeprimes Dim As UByte sieve()   ReDim sieve(max) ' 0 = prime, 1 = no prime sieve(0) = 1 : sieve(1) = 1   For i = 4 To max Step 2 sieve(i) = 1 Next For i = 3 To Sqr(max) +1 Step 2 If sieve(i) = 0 Then For j = i * i To max Step i * 2 sieve(j) = 1 Next End If Next   usc1 = 1 : unsafeprimes = "2" For i = 3 To 3001 Step 2 If sieve(i) = 0 Then If sieve(i \ 2) = 0 Then sc1 += 1 If sc1 <= 35 Then safeprimes += " " + Str(i) End If Else usc1 += 1 If usc1 <= 40 Then unsafeprimes += " " + Str(i) End If End If End If Next   For i = 3003 To max \ 10 Step 2 If sieve(i) = 0 Then If sieve(i \ 2) = 0 Then sc1 += 1 Else usc1 += 1 End If End If Next   sc2 = sc1 : usc2 = usc1 For i = max \ 10 +1 To max Step 2 If sieve(i) = 0 Then If sieve(i \ 2) = 0 Then sc2 += 1 Else usc2 += 1 End If End If Next   Print "the first 35 Safeprimes are: "; safeprimes Print Print "the first 40 Unsafeprimes are: "; unsafeprimes Print Print " Safeprimes Unsafeprimes" Print " Below ---------------------------" Print Using "##########, "; max \ 10; sc1; usc1 Print Using "##########, "; max  ; sc2; usc2   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#OCaml
OCaml
type 'a btree = Leaf of 'a | BTree of ('a btree * 'a btree)   let rec next = function | [] -> None | h :: t -> match h with | Leaf x -> Some (x,t) | BTree(a,b) -> next (a::b::t)   let samefringe t1 t2 = let rec aux s1 s2 = match (next s1, next s2) with | None, None -> true | None, _ | _, None -> false | Some(a,b), Some(c,d) -> (a=c) && aux b d in aux [t1] [t2]   (* Test: *) let () = let u = BTree(Leaf 1, BTree(Leaf 2, Leaf 3)) in let v = BTree(BTree(Leaf 1, Leaf 2), Leaf 3) in let w = BTree(BTree(Leaf 3, Leaf 2), Leaf 1) in let check a b = print_endline (if samefringe a b then "same" else "different") in check u v; check v u; check v w;
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#MUMPS
MUMPS
ERATO1(HI)  ;performs the Sieve of Erotosethenes up to the number passed in.  ;This version sets an array containing the primes SET HI=HI\1 KILL ERATO1 ;Don't make it new - we want it to remain after we quit the function NEW I,J,P FOR I=2:1:(HI**.5)\1 FOR J=I*I:I:HI SET P(J)=1 FOR I=2:1:HI S:'$DATA(P(I)) ERATO1(I)=I KILL I,J,P QUIT
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Phix
Phix
procedure solve(integer sailors) integer m, sm1 = sailors-1 if sm1=0 then -- edge condition for solve(1) [ avoid /0 ] m = sailors else for n=sailors to 1_000_000_000 by sailors do -- morning pile divisible by #sailors m = n for j=1 to sailors do -- see if all of the sailors could.. if remainder(m,sm1)!=0 then -- ..have pushed together sm1 piles m = 0 -- (no: try a higher n) exit end if m = sailors*m/sm1+1 -- add sailor j's stash and one for the monkey end for if m!=0 then exit end if end for end if printf(1,"Solution with %d sailors: %d\n",{sailors,m}) for i=1 to sailors do m -= 1 -- one for the monkey m /= sailors printf(1,"Sailor #%d takes %d, giving 1 to the monkey and leaving %d\n",{i,m,m*sm1}) m *= (sm1) end for printf(1,"In the morning each sailor gets %d nuts\n",m/sailors) end procedure solve(5) solve(6)
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Haskell
Haskell
import Data.List (findIndex, find)   data City = City { name :: String , population :: Float } deriving (Read, Show)   -- CITY PROPERTIES ------------------------------------------------------------ cityName :: City -> String cityName (City x _) = x   cityPop :: City -> Float cityPop (City _ x) = x   mbCityName :: Maybe City -> Maybe String mbCityName (Just x) = Just (cityName x) mbCityName _ = Nothing   mbCityPop :: Maybe City -> Maybe Float mbCityPop (Just x) = Just (cityPop x) mbCityPop _ = Nothing   -- EXAMPLES ------------------------------------------------------------------- mets :: [City] mets = [ City { name = "Lagos" , population = 21.0 } , City { name = "Cairo" , population = 15.2 } , City { name = "Kinshasa-Brazzaville" , population = 11.3 } , City { name = "Greater Johannesburg" , population = 7.55 } , City { name = "Mogadishu" , population = 5.85 } , City { name = "Khartoum-Omdurman" , population = 4.98 } , City { name = "Dar Es Salaam" , population = 4.7 } , City { name = "Alexandria" , population = 4.58 } , City { name = "Abidjan" , population = 4.4 } , City { name = "Casablanca" , population = 3.98 } ]   -- TEST ----------------------------------------------------------------------- main :: IO () main = do mbPrint $ findIndex (("Dar Es Salaam" ==) . cityName) mets mbPrint $ mbCityName $ find ((< 5.0) . cityPop) mets mbPrint $ mbCityPop $ find (("A" ==) . take 1 . cityName) mets   mbPrint :: Show a => Maybe a -> IO () mbPrint (Just x) = print x mbPrint x = print x
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Racket
Racket
  #lang racket   ;; 1. Racket has exact unlimited integers and fractions, which can be ;; used to perform exact operations. For example, given an inexact ;; flonum, we can convert it to an exact fraction and work with that: (define (exact+ x y) (+ (inexact->exact x) (inexact->exact y))) ;; (A variant of this would be to keep all numbers exact, so the default ;; operations never get to inexact numbers)   ;; 2. We can implement the required operation using a bunch of ;; functionality provided by the math library, for example, use ;; `flnext' and `flprev' to get the surrounding numbers for both ;; inputs and use them to produce the resulting interval: (require math) (define (interval+ x y) (cons (+ (flprev x) (flprev y)) (+ (flnext x) (flnext y)))) (interval+ 1.14 2000.0) ; -> '(2001.1399999999999 . 2001.1400000000003) ;; (Note: I'm not a numeric expert in any way, so there must be room for ;; improvement here...)   ;; 3. Yet another option is to use the math library's bigfloats, with an ;; arbitrary precision: (bf-precision 1024) ; 1024 bit floats ;; add two numbers, specified as strings to avoid rounding of number ;; literals (bf+ (bf "1.14") (bf "2000.0"))  
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Raku
Raku
say "Floating points: (Nums)"; say "Error: " ~ (2**-53).Num;   sub infix:<±+> (Num $a, Num $b) { my \ε = (2**-53).Num; $a - ε + $b, $a + ε + $b, }   printf "%4.16f .. %4.16f\n", (1.14e0 ±+ 2e3);   say "\nRationals:";   say ".1 + .2 is exactly equal to .3: ", .1 + .2 === .3;   say "\nLarge denominators require explicit coercion to FatRats:"; say "Sum of inverses of the first 500 natural numbers:"; my $sum = sum (1..500).map: { FatRat.new(1,$_) }; say $sum; say $sum.nude;   { say "\nRat stringification may not show full precision for terminating fractions by default."; say "Use a module to get full precision."; use Rat::Precise; # module loading is scoped to the enclosing block my $rat = 1.5**63; say "\nRaku default stringification for 1.5**63:\n" ~ $rat; # standard stringification say "\nRat::Precise stringification for 1.5**63:\n" ~$rat.precise; # full precision }
http://rosettacode.org/wiki/Ruth-Aaron_numbers
Ruth-Aaron numbers
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum. A Ruth–Aaron triple consists of three consecutive integers with the same properties. There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits. It is common to refer to each Ruth–Aaron group by the first number in it. Task Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors). Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors). Stretch Find and show the first Ruth-Aaron triple (factors). Find and show the first Ruth-Aaron triple (divisors). See also Wikipedia: Ruth–Aaron pair OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1 OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
#J
J
NB. using factors 30{.1 2+/~I. 2 =/\ +/@q: 1+i.100000 5 6 8 9 15 16 77 78 125 126 714 715 948 949 1330 1331 1520 1521 1862 1863 2491 2492 3248 3249 4185 4186 4191 4192 5405 5406 5560 5561 5959 5960 6867 6868 8280 8281 8463 8464 10647 10648 12351 12352 14587 14588 16932 16933 17080 17081 18490 18491 20450 20451 24895 24896 26642 26643 26649 26650   NB. using divisors 30{.1 2+/~I. 2 =/\ (+/@{.@q:~&__) 1+i.100000 5 6 24 25 49 50 77 78 104 105 153 154 369 370 492 493 714 715 1682 1683 2107 2108 2299 2300 2600 2601 2783 2784 5405 5406 6556 6557 6811 6812 8855 8856 9800 9801 12726 12727 13775 13776 18655 18656 21183 21184 24024 24025 24432 24433 24880 24881 25839 25840 26642 26643 35456 35457 40081 40082
http://rosettacode.org/wiki/Ruth-Aaron_numbers
Ruth-Aaron numbers
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum. A Ruth–Aaron triple consists of three consecutive integers with the same properties. There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits. It is common to refer to each Ruth–Aaron group by the first number in it. Task Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors). Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors). Stretch Find and show the first Ruth-Aaron triple (factors). Find and show the first Ruth-Aaron triple (divisors). See also Wikipedia: Ruth–Aaron pair OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1 OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
#Julia
Julia
using Lazy using Primes   sumprimedivisors(n) = sum([p[1] for p in factor(n)]) ruthaaron(n) = sumprimedivisors(n) == sumprimedivisors(n + 1) ruthaarontriple(n) = sumprimedivisors(n) == sumprimedivisors(n + 1) == sumprimedivisors(n + 2)   sumprimefactors(n) = sum([p[1] * p[2] for p in factor(n)]) ruthaaronfactors(n) = sumprimefactors(n) == sumprimefactors(n + 1) ruthaaronfactorstriple(n) = sumprimefactors(n) == sumprimefactors(n + 1) == sumprimefactors(n + 2)   raseq = @>> Lazy.range() filter(ruthaaron) rafseq = @>> Lazy.range() filter(ruthaaronfactors)   println("30 Ruth Aaron numbers:") foreach(p -> print(lpad(p[2], 6), p[1] % 10 == 0 ? "\n" : ""), enumerate(collect(take(30, raseq))))   println("\n30 Ruth Aaron factor numbers:") foreach(p -> print(lpad(p[2], 6), p[1] % 10 == 0 ? "\n" : ""), enumerate(collect(take(30, rafseq))))   println("\nRuth Aaron triple starts at: ", findfirst(ruthaarontriple, 1:100000000)) println("\nRuth Aaron factor triple starts at: ", findfirst(ruthaaronfactorstriple, 1:10000000))  
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#ALGOL_68
ALGOL 68
FORMAT hay stack := $c("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")$;   FILE needle exception; STRING ref needle; associate(needle exception, ref needle);   PROC index = (FORMAT haystack, REF STRING needle)INT:( INT out; ref needle := needle; getf(needle exception,(haystack, out)); out );   test:( []STRING needles = ("Washington","Bush"); FOR i TO UPB needles DO STRING needle := needles[i]; on value error(needle exception, (REF FILE f)BOOL: value error); printf(($d" "gl$,index(hay stack, needle), needle)); end on value error; value error: printf(($g" "gl$,needle, "is not in haystack")); end on value error: reset(needle exception) OD )
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#BASIC
BASIC
100 DEF PROC graph f$ 110 LOCAL x,y 120 PLOT 0,90 130 FOR x = -2 TO 2 STEP 0.02 140 LET y = VAL(f$) 150 DRAW TO x*50+100, y*50+90 160 NEXT x 170 END PROC
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#BBC_BASIC
BBC BASIC
expr$ = "PI^2 + 1" PRINT EVAL(expr$)
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Burlesque
Burlesque
  blsq ) {5 5 .+}e! 10  
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Frink
Frink
  safePrimes[end=undef] := select[primes[5,end], {|p| isPrime[(p-1)/2] }] unsafePrimes[end=undef] := select[primes[2,end], {|p| p<5 or isPrime[(p-1)/2] }]   println["First 35 safe primes: " + first[safePrimes[], 35]] println["Safe primes below 1,000,000: " + length[safePrimes[1_000_000]]] println["Safe primes below 10,000,000: " + length[safePrimes[10_000_000]]]   println["First 40 unsafe primes: " + first[unsafePrimes[], 40]] println["Unsafe primes below 1,000,000: " + length[unsafePrimes[1_000_000]]] println["Unsafe primes below 10,000,000: " + length[unsafePrimes[10_000_000]]]  
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Go
Go
package main   import "fmt"   func sieve(limit uint64) []bool { limit++ // True denotes composite, false denotes prime. c := make([]bool, limit) // all false by default c[0] = true c[1] = true // apart from 2 all even numbers are of course composite for i := uint64(4); i < limit; i += 2 { c[i] = true } p := uint64(3) // Start from 3. for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c }   func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s }   func main() { // sieve up to 10 million sieved := sieve(1e7) var safe = make([]int, 35) count := 0 for i := 3; count < 35; i += 2 { if !sieved[i] && !sieved[(i-1)/2] { safe[count] = i count++ } } fmt.Println("The first 35 safe primes are:\n", safe, "\n")   count = 0 for i := 3; i < 1e6; i += 2 { if !sieved[i] && !sieved[(i-1)/2] { count++ } } fmt.Println("The number of safe primes below 1,000,000 is", commatize(count), "\n")   for i := 1000001; i < 1e7; i += 2 { if !sieved[i] && !sieved[(i-1)/2] { count++ } } fmt.Println("The number of safe primes below 10,000,000 is", commatize(count), "\n")   unsafe := make([]int, 40) unsafe[0] = 2 // since (2 - 1)/2 is not prime count = 1 for i := 3; count < 40; i += 2 { if !sieved[i] && sieved[(i-1)/2] { unsafe[count] = i count++ } } fmt.Println("The first 40 unsafe primes are:\n", unsafe, "\n")   count = 1 for i := 3; i < 1e6; i += 2 { if !sieved[i] && sieved[(i-1)/2] { count++ } } fmt.Println("The number of unsafe primes below 1,000,000 is", commatize(count), "\n")   for i := 1000001; i < 1e7; i += 2 { if !sieved[i] && sieved[(i-1)/2] { count++ } } fmt.Println("The number of unsafe primes below 10,000,000 is", commatize(count), "\n") }
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#Perl
Perl
  #!/usr/bin/perl use strict;   my @trees = ( # 0..2 are same [ 'd', [ 'c', [ 'a', 'b', ], ], ], [ [ 'd', 'c' ], [ 'a', 'b' ] ], [ [ [ 'd', 'c', ], 'a', ], 'b', ], # and this one's different! [ [ [ [ [ [ 'a' ], 'b' ], 'c', ], 'd', ], 'e', ], 'f' ], );   for my $tree_idx (1 .. $#trees) { print "tree[",$tree_idx-1,"] vs tree[$tree_idx]: ", cmp_fringe($trees[$tree_idx-1], $trees[$tree_idx]), "\n"; }   sub cmp_fringe { my $ti1 = get_tree_iterator(shift); my $ti2 = get_tree_iterator(shift); while (1) { my ($L, $R) = ($ti1->(), $ti2->()); next if defined($L) and defined($R) and $L eq $R; return "Same" if !defined($L) and !defined($R); return "Different"; } }   sub get_tree_iterator { my @rtrees = (shift); my $tree; return sub { $tree = pop @rtrees; ($tree, $rtrees[@rtrees]) = @$tree while ref $tree; return $tree; } }  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Neko
Neko
/* The Computer Language Shootout http://shootout.alioth.debian.org/   contributed by Nicolas Cannasse */ fmt = function(i) { var s = $string(i); while( $ssize(s) < 8 ) s = " "+s; return s; } nsieve = function(m) { var a = $amake(m); var count = 0; var i = 2; while( i < m ) { if $not(a[i]) { count += 1; var j = (i << 1); while( j < m ) { if( $not(a[j]) ) a[j] = true; j += i; } } i += 1; } $print("Primes up to ",fmt(m)," ",fmt(count),"\n"); }   var n = $int($loader.args[0]); if( n == null ) n = 2; var i = 0; while( i < 3 ) { nsieve(10000 << (n - i)); i += 1; }
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Picat
Picat
main ?=> between(2,9,N),  % N: number of sailors once s(N), fail. main => true.   s(N) => next_candidate(N+1,N,C),  % C: original number of coconuts divide(N,N,C,Cr),  % Cr: remainder printf("%d: original = %d, remainder = %d, final share = %d\n",N,C,Cr,Cr div N).   next_candidate(From,_Step,X) ?=> X = From. next_candidate(From,Step,X) => next_candidate(From+Step,Step,X).   divide(N,0,C,Cr) => C > 0, C mod N == 0, Cr = C. divide(N,I,C,Cr) => (C-1) mod N == 0, Q = (C-1) div N, C1 = Q*(N-1), divide(N,I-1,C1,Cr).  
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Python
Python
def monkey_coconuts(sailors=5): "Parameterised the number of sailors using an inner loop including the last mornings case" nuts = sailors while True: n0, wakes = nuts, [] for sailor in range(sailors + 1): portion, remainder = divmod(n0, sailors) wakes.append((n0, portion, remainder)) if portion <= 0 or remainder != (1 if sailor != sailors else 0): nuts += 1 break n0 = n0 - portion - remainder else: break return nuts, wakes   if __name__ == "__main__": for sailors in [5, 6]: nuts, wake_stats = monkey_coconuts(sailors) print("\nFor %i sailors the initial nut count is %i" % (sailors, nuts)) print("On each waking, the nut count, portion taken, and monkeys share are:\n ", ',\n '.join(repr(ws) for ws in wake_stats))
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#J
J
colnumeric=: 0&".&.>@{`[`]}   data=: 1 colnumeric |: fixcsv 0 :0 Lagos, 21 Cairo, 15.2 Kinshasa-Brazzaville, 11.3 Greater Johannesburg, 7.55 Mogadishu, 5.85 Khartoum-Omdurman, 4.98 Dar Es Salaam, 4.7 Alexandria, 4.58 Abidjan, 4.4 Casablanca, 3.98 )
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Java
Java
import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate;   /** * Represent a City and it's population. * City-Objects do have a natural ordering, they are ordered by their poulation (descending) */ class City implements Comparable<City> { private final String name; private final double population;   City(String name, double population) { this.name = name; this.population = population; }   public String getName() { return this.name; }   public double getPopulation() { return this.population; }   @Override public int compareTo(City o) { //compare for descending order. for ascending order, swap o and this return Double.compare(o.population, this.population); } }   public class SearchListOfRecords {   public static void main(String[] args) {   //Array-of-City-Objects-Literal City[] datasetArray = {new City("Lagos", 21.), new City("Cairo", 15.2), new City("Kinshasa-Brazzaville", 11.3), new City("Greater Johannesburg", 7.55), new City("Mogadishu", 5.85), new City("Khartoum-Omdurman", 4.98), new City("Dar Es Salaam", 4.7), new City("Alexandria", 4.58), new City("Abidjan", 4.4), new City("Casablanca", 3.98)};   //Since this is about "collections smarter that arrays", the Array is converted to a List List<City> dataset = Arrays.asList(datasetArray);   //the City-Objects know that they are supposed to be compared by population Collections.sort(dataset);     //Find the first City that matches the given predicate and print it's index in the dataset //the Predicate here is given in the form a Java 8 Lambda that returns true if the given name //Note that the Predicate is not limited to searching for names. It can operate on anything one can done with // and compared about City-Objects System.out.println(findIndexByPredicate(dataset, city -> city.getName().equals("Dar Es Salaam")));   //Find the first City whose population matches the given Predicate (here: population <= 5.) and print it's name //here the value is returned an printed by the caller System.out.println(findFirstCityByPredicate(dataset, city -> city.getPopulation() <= 5.));   //Find the first City that matches the given predicate (here: name starts with "A") and //apply the given consumer (here: print the city's population) //here the caller specifies what to do with the object. This is the most generic solution and could also be used to solve Task 2 applyConsumerByPredicate(dataset, city -> city.getName().startsWith("A"), city -> System.out.println(city.getPopulation()));   }   /** * Finds a City by Predicate. * The predicate can be anything that can be done or compared about a City-Object. * <p> * Since the task was to "find the index" it is not possible to use Java 8's stream facilities to solve this. * The Predicate is used very explicitly here - this is unusual. * * @param dataset the data to operate on, assumed to be sorted * @param p the Predicate that wraps the search term. * @return the index of the City in the dataset */ public static int findIndexByPredicate(List<City> dataset, Predicate<City> p) { for (int i = 0; i < dataset.size(); i++) { if (p.test(dataset.get(i))) return i; } return -1; }   /** * Finds and returns the name of the first City where the population matches the Population-Predicate. * This solutions makes use of Java 8's stream facilities. * * @param dataset the data to operate on, assumed to be sorted * @param predicate a predicate that specifies the city searched. Can be "any predicate that can be applied to a City" * @return the name of the first City in the dataset whose population matches the predicate */ private static String findFirstCityByPredicate(List<City> dataset, Predicate<City> predicate) { //turn the List into a Java 8 stream, so it can used in stream-operations //filter() by the specified predicate (to the right of this operation, only elements matching the predicate are left in the stream) //find the first element (which is "the first city..." from the task) //get() the actualy object (this is necessary because it is wrapped in a Java 8 Optional<T> //getName() the name and return it. return dataset.stream().filter(predicate).findFirst().get().getName(); }   /** * In specified dataset, find the first City whose name matches the specified predicate, and apply the specified consumer * <p> * Since this can be solved pretty much like the "find a city by population", this has been varied. The caller specifies what to do with the result. * So this method does not return anything, but requiers a "consumer" that processes the result. * * @param dataset the data to operate on, assumed to be sorted * @param predicate a predicate that specifies the city searched. Can be "any predicate that can be applied to a City" * @param doWithResult a Consumer that specified what to do with the results */ private static void applyConsumerByPredicate(List<City> dataset, Predicate<City> predicate, Consumer<City> doWithResult) { //turn the List in to a Java 8 stream in stream-operations //filter() by the specified predicate (to the right of this operation, only elements matching the predicate are left in the stream) //find the first element (which is "the first city..." from the task) // if there is an element found, feed it to the Consumer dataset.stream().filter(predicate).findFirst().ifPresent(doWithResult); } }  
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#REXX
REXX
numeric digits 1000 /*defines precision to be 1,000 decimal digits. */   y=digits() /*sets Y to existing number of decimal digits.*/   numeric digits y + y%10 /*increase the (numeric) decimal digits by 10%.*/
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Ruby
Ruby
require 'bigdecimal' require 'bigdecimal/util' # String#to_d   def safe_add(a, b, prec) a, b = a.to_d, b.to_d rm = BigDecimal::ROUND_MODE orig = BigDecimal.mode(rm)   BigDecimal.mode(rm, BigDecimal::ROUND_FLOOR) low = a.add(b, prec)   BigDecimal.mode(rm, BigDecimal::ROUND_CEILING) high = a.add(b, prec)   BigDecimal.mode(rm, orig) low..high end   [["1", "2"], ["0.1", "0.2"], ["0.1", "0.00002"], ["0.1", "-0.00002"], ].each { |a, b| puts "#{a} + #{b} = #{safe_add(a, b, 3)}" }
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Scala
Scala
object SafeAddition extends App { val (a, b) = (1.2, 0.03) val result = safeAdd(a, b)   private def safeAdd(a: Double, b: Double) = Seq(stepDown(a + b), stepUp(a + b))   private def stepDown(d: Double) = Math.nextAfter(d, Double.NegativeInfinity)   private def stepUp(d: Double) = Math.nextUp(d)   println(f"($a%.2f + $b%.2f) is in the range ${result.head}%.16f .. ${result.last}%.16f")   }
http://rosettacode.org/wiki/Ruth-Aaron_numbers
Ruth-Aaron numbers
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum. A Ruth–Aaron triple consists of three consecutive integers with the same properties. There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits. It is common to refer to each Ruth–Aaron group by the first number in it. Task Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors). Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors). Stretch Find and show the first Ruth-Aaron triple (factors). Find and show the first Ruth-Aaron triple (divisors). See also Wikipedia: Ruth–Aaron pair OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1 OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
#Pascal
Pascal
program RuthAaronNumb; // gets factors of consecutive integers fast // limited to 1.2e11 {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$COPERATORS ON} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils, strutils //Numb2USA {$IFDEF WINDOWS},Windows{$ENDIF} ; //###################################################################### //prime decomposition const //HCN(86) > 1.2E11 = 128,501,493,120 count of divs = 4096 7 3 1 1 1 1 1 1 1 HCN_DivCnt = 4096; //used odd size for test only SizePrDeFe = 32768;//*72 <= 64kb level I or 2 Mb ~ level 2 cache type tItem = Uint64; tDivisors = array [0..HCN_DivCnt] of tItem; tpDivisor = pUint64;   tdigits = array [0..31] of Uint32; //the first number with 11 different prime factors = //2*3*5*7*11*13*17*19*23*29*31 = 2E11 //56 byte tprimeFac = packed record pfSumOfDivs, pfRemain : Uint64; pfDivCnt : Uint32; pfMaxIdx : Uint32; pfpotPrimIdx : array[0..9] of word; pfpotMax : array[0..11] of byte; end; tpPrimeFac = ^tprimeFac;   tPrimeDecompField = array[0..SizePrDeFe-1] of tprimeFac; tPrimes = array[0..65535] of Uint32;   var {$ALIGN 8} SmallPrimes: tPrimes; {$ALIGN 32} PrimeDecompField :tPrimeDecompField; pdfIDX,pdfOfs: NativeInt;   procedure InitSmallPrimes; //get primes. #0..65535.Sieving only odd numbers const MAXLIMIT = (821641-1) shr 1; var pr : array[0..MAXLIMIT] of byte; p,j,d,flipflop :NativeUInt; Begin SmallPrimes[0] := 2; fillchar(pr[0],SizeOf(pr),#0); p := 0; repeat repeat p +=1 until pr[p]= 0; j := (p+1)*p*2; if j>MAXLIMIT then BREAK; d := 2*p+1; repeat pr[j] := 1; j += d; until j>MAXLIMIT; until false;   SmallPrimes[1] := 3; SmallPrimes[2] := 5; j := 3; d := 7; flipflop := (2+1)-1;//7+2*2,11+2*1,13,17,19,23 p := 3; repeat if pr[p] = 0 then begin SmallPrimes[j] := d; inc(j); end; d += 2*flipflop; p+=flipflop; flipflop := 3-flipflop; until (p > MAXLIMIT) OR (j>High(SmallPrimes)); end;   function OutPots(pD:tpPrimeFac;n:NativeInt):Ansistring; var s: String[31]; chk,p,i: NativeInt; Begin str(n,s); result := Format('%15s : ',[Numb2USA(s)]);   with pd^ do begin chk := 1; For n := 0 to pfMaxIdx-1 do Begin if n>0 then result += '*'; p := SmallPrimes[pfpotPrimIdx[n]]; chk *= p; str(p,s); result += s; i := pfpotMax[n]; if i >1 then Begin str(pfpotMax[n],s); result += '^'+s; repeat chk *= p; dec(i); until i <= 1; end; end; p := pfRemain; If p >1 then Begin str(p,s); chk *= p; result += '*'+s; end; end; end;   function CnvtoBASE(var dgt:tDigits;n:Uint64;base:NativeUint):NativeInt; //n must be multiple of base aka n mod base must be 0 var q,r: Uint64; i : NativeInt; Begin fillchar(dgt,SizeOf(dgt),#0); i := 0; n := n div base; result := 0; repeat r := n; q := n div base; r -= q*base; n := q; dgt[i] := r; inc(i); until (q = 0); //searching lowest pot in base result := 0; while (result<i) AND (dgt[result] = 0) do inc(result); inc(result); end;   function IncByBaseInBase(var dgt:tDigits;base:NativeInt):NativeInt; var q :NativeInt; Begin result := 0; q := dgt[result]+1; if q = base then repeat dgt[result] := 0; inc(result); q := dgt[result]+1; until q <> base; dgt[result] := q; result +=1; end;   function SieveOneSieve(var pdf:tPrimeDecompField):boolean; var dgt:tDigits; i,j,k,pr,fac,n,MaxP : Uint64; begin n := pdfOfs; if n+SizePrDeFe >= sqr(SmallPrimes[High(SmallPrimes)]) then EXIT(FALSE); //init for i := 0 to SizePrDeFe-1 do begin with pdf[i] do Begin pfDivCnt := 1; pfSumOfDivs := 1; pfRemain := n+i; pfMaxIdx := 0; pfpotPrimIdx[0] := 0; pfpotMax[0] := 0; end; end; //first factor 2. Make n+i even i := (pdfIdx+n) AND 1; IF (n = 0) AND (pdfIdx<2) then i := 2;   repeat with pdf[i] do begin j := BsfQWord(n+i); pfMaxIdx := 1; pfpotPrimIdx[0] := 0; pfpotMax[0] := j; pfRemain := (n+i) shr j; pfSumOfDivs := (Uint64(1) shl (j+1))-1; pfDivCnt := j+1; end; i += 2; until i >=SizePrDeFe; //i now index in SmallPrimes i := 0; maxP := trunc(sqrt(n+SizePrDeFe))+1; repeat //search next prime that is in bounds of sieve if n = 0 then begin repeat inc(i); pr := SmallPrimes[i]; k := pr-n MOD pr; if k < SizePrDeFe then break; until pr > MaxP; end else begin repeat inc(i); pr := SmallPrimes[i]; k := pr-n MOD pr; if (k = pr) AND (n>0) then k:= 0; if k < SizePrDeFe then break; until pr > MaxP; end;   //no need to use higher primes if pr*pr > n+SizePrDeFe then BREAK;   //j is power of prime j := CnvtoBASE(dgt,n+k,pr); repeat with pdf[k] do Begin pfpotPrimIdx[pfMaxIdx] := i; pfpotMax[pfMaxIdx] := j; pfDivCnt *= j+1; fac := pr; repeat pfRemain := pfRemain DIV pr; dec(j); fac *= pr; until j<= 0; pfSumOfDivs *= (fac-1)DIV(pr-1); inc(pfMaxIdx); k += pr; j := IncByBaseInBase(dgt,pr); end; until k >= SizePrDeFe; until false;   //correct sum of & count of divisors for i := 0 to High(pdf) do Begin with pdf[i] do begin j := pfRemain; if j <> 1 then begin pfSumOFDivs *= (j+1); pfDivCnt *=2; end; end; end; result := true; end;   function NextSieve:boolean; begin dec(pdfIDX,SizePrDeFe); inc(pdfOfs,SizePrDeFe); result := SieveOneSieve(PrimeDecompField); end;   function GetNextPrimeDecomp:tpPrimeFac; begin if pdfIDX >= SizePrDeFe then if Not(NextSieve) then EXIT(NIL); result := @PrimeDecompField[pdfIDX]; inc(pdfIDX); end;   function Init_Sieve(n:NativeUint):boolean; //Init Sieve pdfIdx,pdfOfs are Global begin pdfIdx := n MOD SizePrDeFe; pdfOfs := n-pdfIdx; result := SieveOneSieve(PrimeDecompField); end; //end prime decomposition //######################################################################   procedure Get_RA_Prime(cntlimit:NativeUInt;useFactors:Boolean); var pPrimeDecomp :tpPrimeFac; pr,sum0,sum1,n,i,cnt : NativeUInt; begin write('First 30 Ruth-Aaron numbers ('); if useFactors then writeln('factors ):') else writeln('divisors ):');   cnt := 0; sum1:= 0; n := 2; Init_Sieve(n); repeat pPrimeDecomp:= GetNextPrimeDecomp; with pPrimeDecomp^ do begin sum0:= pfRemain; //if not(prime) if (sum0 <> n) then begin if sum0 = 1 then sum0 := 0; For i := 0 to pfMaxIdx-1 do begin pr := smallprimes[pfpotPrimIdx[i]]; if useFactors then sum0 += pr*pfpotMax[i] else sum0 += pr; end; if sum1 = sum0 then begin write(n-1:10); inc(cnt); if cnt mod 8 = 0 then writeln; end; sum1 := sum0; end else sum1:= 0; end; inc(n); until cnt>=cntlimit; writeln; end;   function findfirstTripplesFactor(useFactors:boolean):NativeUint; var pPrimeDecomp :tpPrimeFac; pr,sum0,sum1,sum2,i : NativeUInt; begin sum1:= 0; sum2:= 0; result:= 2; Init_Sieve(result); repeat pPrimeDecomp:= GetNextPrimeDecomp; with pPrimeDecomp^ do begin sum0:= pfRemain; //if not(prime) if (sum0 <> result) then begin if sum0 = 1 then sum0 := 0; For i := 0 to pfMaxIdx-1 do begin pr := smallprimes[pfpotPrimIdx[i]]; if useFactors then pr *= pfpotMax[i]; sum0 += pr end; if (sum2 = sum0) AND (sum1=sum0) then Exit(result-2); end else sum0 := 0; sum2:= sum1; sum1 := sum0; end; inc(result); until false end;   Begin InitSmallPrimes; Get_RA_Prime(30,false); Get_RA_Prime(30,true); writeln; writeln('First Ruth-Aaron triple (factors) :'); writeln(findfirstTripplesFactor(true):10); writeln; writeln('First Ruth-Aaron triple (divisors):'); writeln(findfirstTripplesFactor(false):10); end.
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Arturo
Arturo
haystack: [Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo]   loop [Bush Washington] 'needle [ i: index haystack needle   if? empty? i -> panic ~"|needle| is not in haystack" else -> print [i needle] ]
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Cach.C3.A9_ObjectScript
Caché ObjectScript
USER>Set cmd="Write ""Hello, World!""" USER>Xecute cmd Hello, World! USER>Set fnc="(num1, num2) Set res=num1+num2 Quit res" USER>Write $Xecute(fnc, 2, 3) 5
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Common_Lisp
Common Lisp
(eval '(+ 4 5)) ; returns 9
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
!run-blob !compile-string "(fake filename)" "!print \qHello world\q"
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Haskell
Haskell
  import Text.Printf (printf) import Data.Numbers.Primes (isPrime, primes)   main = do printf "First 35 safe primes: %s\n" (show $ take 35 safe) printf "There are %d safe primes below 100,000.\n" (length $ takeWhile (<1000000) safe) printf "There are %d safe primes below 10,000,000.\n\n" (length $ takeWhile (<10000000) safe)   printf "First 40 unsafe primes: %s\n" (show $ take 40 unsafe) printf "There are %d unsafe primes below 100,000.\n" (length $ takeWhile (<1000000) unsafe) printf "There are %d unsafe primes below 10,000,000.\n\n" (length $ takeWhile (<10000000) unsafe)   where safe = filter (\n -> isPrime ((n-1) `div` 2)) primes unsafe = filter (\n -> not (isPrime((n-1) `div` 2))) primes  
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#Phix
Phix
-- -- demo\rosetta\Same_Fringe.exw -- ============================ -- -- In some cases it may help to replace the single res with a table, such -- that if you have concurrent task pairs {1,2} and {3,4} with a table of -- result indexes ridx = {1,1,2,2}, then each updates res[ridx[tidx]]. In -- other words if extending tasks[] rather than overwriting it, you would -- also extend res[] and ridx[] and sdata[], and need freelist handling. -- without js -- (multitasking) constant tests = {{0,1,{0,2,0}}, {{0,1,0},2,0}, {{0,1,0},2,{0,3,0}}, } sequence tasks, sdata = repeat(0,2) integer res = 0, active_tasks bool show_details = true procedure scan(sequence tree, integer level, integer tidx) object {left,data,right} = tree if res=0 then if left!=0 then scan(left,level+1,tidx) end if sdata[tidx] = data if show_details then printf(1,"task[%d] sets sdata[%d] to %v\n",{tidx,tidx,data}) end if if res=0 then task_suspend(task_self()) task_yield() end if if right!=0 then scan(right,level+1,tidx) end if end if if level=1 then if show_details then printf(1,"task[%d] ends\n",tidx) end if active_tasks -= 1 tasks[tidx] = 0 sdata[tidx] = -1 -- (or use a separate flag or tasks[tidx]) end if end procedure procedure test(integer t1, t2) tasks = {task_create(routine_id("scan"),{tests[t1],1,1}), task_create(routine_id("scan"),{tests[t2],1,2})} active_tasks = 2 res = 0 while active_tasks>0 do for i=1 to 2 do if tasks[i] then task_schedule(tasks[i],1) task_yield() end if end for if res=0 then -- (nb next might only be valid for active_tasks==2) res = compare(sdata[1],sdata[2]) if show_details then printf(1,"compare(%v,%v) ==> %d, active tasks:%d\n", {sdata[1],sdata[2],res,active_tasks}) end if end if end while printf(1,"test(%d,%d):%d\n",{t1,t2,res}) end procedure ?"started" for l=1 to 3 do for r=1 to 3 do test(l,r) show_details = 0 end for end for ?"done" {} = wait_key()
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols binary   parse arg loWatermark hiWatermark . if loWatermark = '' | loWatermark = '.' then loWatermark = 1 if hiWatermark = '' | hiWatermark = '.' then hiWatermark = 200   do if \loWatermark.datatype('w') | \hiWatermark.datatype('w') then - signal NumberFormatException('arguments must be whole numbers') if loWatermark > hiWatermark then - signal IllegalArgumentException('the start value must be less than the end value')   seive = sieveOfEratosthenes(hiWatermark) primes = getPrimes(seive, loWatermark, hiWatermark).strip   say 'List of prime numbers from' loWatermark 'to' hiWatermark 'via a "Sieve of Eratosthenes" algorithm:' say ' 'primes.changestr(' ', ',') say ' Count of primes:' primes.words catch ex = Exception ex.printStackTrace end   return   method sieveOfEratosthenes(hn = long) public static binary returns Rexx   sv = Rexx(isTrue) sv[1] = isFalse ix = long jx = long   loop ix = 2 while ix * ix <= hn if sv[ix] then loop jx = ix * ix by ix while jx <= hn sv[jx] = isFalse end jx end ix   return sv   method getPrimes(seive = Rexx, lo = long, hi = long) private constant binary returns Rexx   primes = Rexx('') loop p_ = lo to hi if \seive[p_] then iterate p_ primes = primes p_ end p_   return primes   method isTrue public constant binary returns boolean return 1 == 1   method isFalse public constant binary returns boolean return \isTrue  
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#R
R
coconutsProblem <- function(sailorCount) { stopifnot(sailorCount > 1) #Problem makes no sense otherwise initalCoconutCount <- sailorCount repeat { initalCoconutCount <- initalCoconutCount + 1 coconutCount <- initalCoconutCount for(i in seq_len(sailorCount)) { if(coconutCount %% sailorCount != 1) break coconutCount <- (coconutCount - 1) * (sailorCount - 1)/sailorCount if(i == sailorCount && coconutCount > 0 && coconutCount %% sailorCount == 0) return(initalCoconutCount) } } } print(data.frame("Sailors" = 2:8, "Coconuts" = sapply(2:8, coconutsProblem)))
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Racket
Racket
#lang racket   (define (wake-and-split nuts sailors depth wakes) (define-values (portion remainder) (quotient/remainder nuts sailors)) (define monkey (if (zero? depth) 0 1)) (define new-wakes (cons (list nuts portion remainder) wakes)) (and (positive? portion) (= remainder monkey) (if (zero? depth) new-wakes (wake-and-split (- nuts portion remainder) sailors (sub1 depth) new-wakes))))   (define (sleep-and-split nuts sailors) (wake-and-split nuts sailors sailors '()))   (define (monkey_coconuts (sailors 5)) (let loop ([nuts sailors]) (or (sleep-and-split nuts sailors) (loop (add1 nuts)))))   (for ([sailors (in-range 5 7)]) (define wakes (monkey_coconuts sailors)) (printf "For ~a sailors the initial nut count is ~a\n" sailors (first (last wakes))) (map displayln (reverse wakes)) (newline))
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#JavaScript
JavaScript
(function () { 'use strict';   // find :: (a -> Bool) -> [a] -> Maybe a function find(f, xs) { for (var i = 0, lng = xs.length; i < lng; i++) { if (f(xs[i])) return xs[i]; } return undefined; }   // findIndex :: (a -> Bool) -> [a] -> Maybe Int function findIndex(f, xs) { for (var i = 0, lng = xs.length; i < lng; i++) { if (f(xs[i])) return i; } return undefined; }     var lst = [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ];   return { darEsSalaamIndex: findIndex(function (x) { return x.name === 'Dar Es Salaam'; }, lst),   firstBelow5M: find(function (x) { return x.population < 5; }, lst) .name,   firstApop: find(function (x) { return x.name.charAt(0) === 'A'; }, lst) .population };   })();
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Swift
Swift
let a = 1.2 let b = 0.03   print("\(a) + \(b) is in the range \((a + b).nextDown)...\((a + b).nextUp)")
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Tcl
Tcl
package require critcl package provide stepaway 1.0 critcl::ccode { #include <math.h> #include <float.h> } critcl::cproc stepup {double value} double { return nextafter(value, DBL_MAX); } critcl::cproc stepdown {double value} double { return nextafter(value, -DBL_MAX); }
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the width of the interval   (a +↑ b) - (a +↓ b)   would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise). I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome. Usually a   FPU's   have machine   +,-,*,/   operations accurate within the machine precision. To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points. If the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[. When the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition. Task; Show how   +↓   and   +↑   can be implemented in your language using the standard floating-point type. Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [a +↓ b, a +↑ b].
#Transd
Transd
#lang transd   MainModule : { a: 1.2, b: 0.03,   safeAdd: (λ d Double() e Double() (ret [(decr (+ d e)), (incr (+ d e))])),   _start: (λ (lout "(+ " a " " b ") is in the range: " prec: 20 (safeAdd a b)) ) }
http://rosettacode.org/wiki/Ruth-Aaron_numbers
Ruth-Aaron numbers
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum. A Ruth–Aaron triple consists of three consecutive integers with the same properties. There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits. It is common to refer to each Ruth–Aaron group by the first number in it. Task Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors). Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors). Stretch Find and show the first Ruth-Aaron triple (factors). Find and show the first Ruth-Aaron triple (divisors). See also Wikipedia: Ruth–Aaron pair OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1 OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
#Perl
Perl
#!/usr/bin/perl   use strict; use warnings; use ntheory qw( factor vecsum ); use List::AllUtils qw( uniq );   #use Data::Dump 'dd'; dd factor(6); exit;   my $n = 1; my @answers; while( @answers < 30 ) { vecsum(factor($n)) == vecsum(factor($n+1)) and push @answers, $n; $n++; } print "factors:\n\n@answers\n\n" =~ s/.{60}\K /\n/gr;   $n = 1; @answers = (); while( @answers < 30 ) { vecsum(uniq factor($n)) == vecsum(uniq factor($n+1)) and push @answers, $n; $n++; } print "divisors:\n\n@answers\n" =~ s/.{60}\K /\n/gr;
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#AutoHotkey
AutoHotkey
haystack = Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo needle = bush, washington Loop, Parse, needle, `, { If InStr(haystack, A_LoopField) MsgBox, % A_LoopField Else MsgBox % A_LoopField . " not in haystack" }
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#E
E
? e`1 + 1`.eval(safeScope) # value: 2
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#EchoLisp
EchoLisp
  (eval (list * 6 7)) → 42 (eval '(* 6 7)) ;; quoted argument → 42 (eval (read-from-string "(* 6 7)")) → 42  
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#J
J
NB. play around a bit to get primes less than ten million p:inv 10000000 664579 p:664579 10000019 PRIMES =: p:i.664579 10 {. PRIMES 2 3 5 7 11 13 17 19 23 29 {: PRIMES 9999991 primeQ =: 1&p: safeQ =: primeQ@:-:@:<: Filter =: (#~`)(`:6) SAFE =: safeQ Filter PRIMES NB. first thirty-five safe primes (32+3) {. SAFE 5 7 11 23 47 59 83 107 167 179 227 263 347 359 383 467 479 503 563 587 719 839 863 887 983 1019 1187 1283 1307 1319 1367 1439 1487 1523 1619 NB. first forty unsafe primes (33+7) {. PRIMES -. SAFE 2 3 13 17 19 29 31 37 41 43 53 61 67 71 73 79 89 97 101 103 109 113 127 131 137 139 149 151 157 163 173 181 191 193 197 199 211 223 229 233 NB. tally of safe primes less than ten million # SAFE 30657 NB. tally of safe primes below a million # 1000000&>Filter SAFE 4324 NB. tally of perilous primes below ten million UNSAFE =: PRIMES -. SAFE # UNSAFE 633922 NB. tally of these below one million K =: 1 : 'm * 1000' +/ UNSAFE < 1 K K 74174
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Java
Java
public class SafePrimes { public static void main(String... args) { // Use Sieve of Eratosthenes to find primes int SIEVE_SIZE = 10_000_000; boolean[] isComposite = new boolean[SIEVE_SIZE]; // It's really a flag indicating non-prime, but composite usually applies isComposite[0] = true; isComposite[1] = true; for (int n = 2; n < SIEVE_SIZE; n++) { if (isComposite[n]) { continue; } for (int i = n * 2; i < SIEVE_SIZE; i += n) { isComposite[i] = true; } }   int oldSafePrimeCount = 0; int oldUnsafePrimeCount = 0; int safePrimeCount = 0; int unsafePrimeCount = 0; StringBuilder safePrimes = new StringBuilder(); StringBuilder unsafePrimes = new StringBuilder(); int safePrimesStrCount = 0; int unsafePrimesStrCount = 0; for (int n = 2; n < SIEVE_SIZE; n++) { if (n == 1_000_000) { oldSafePrimeCount = safePrimeCount; oldUnsafePrimeCount = unsafePrimeCount; } if (isComposite[n]) { continue; } boolean isUnsafe = isComposite[(n - 1) >>> 1]; if (isUnsafe) { if (unsafePrimeCount < 40) { if (unsafePrimeCount > 0) { unsafePrimes.append(", "); } unsafePrimes.append(n); unsafePrimesStrCount++; } unsafePrimeCount++; } else { if (safePrimeCount < 35) { if (safePrimeCount > 0) { safePrimes.append(", "); } safePrimes.append(n); safePrimesStrCount++; } safePrimeCount++; } }   System.out.println("First " + safePrimesStrCount + " safe primes: " + safePrimes.toString()); System.out.println("Number of safe primes below 1,000,000: " + oldSafePrimeCount); System.out.println("Number of safe primes below 10,000,000: " + safePrimeCount); System.out.println("First " + unsafePrimesStrCount + " unsafe primes: " + unsafePrimes.toString()); System.out.println("Number of unsafe primes below 1,000,000: " + oldUnsafePrimeCount); System.out.println("Number of unsafe primes below 10,000,000: " + unsafePrimeCount);   return; } }
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#PicoLisp
PicoLisp
(de nextLeaf (Rt Tree) (co Rt (recur (Tree) (when Tree (recurse (cadr Tree)) (yield (car Tree)) (recurse (cddr Tree)) ) ) ) )   (de cmpTrees (Tree1 Tree2) (prog1 (use (Node1 Node2) (loop (setq Node1 (nextLeaf "rt1" Tree1) Node2 (nextLeaf "rt2" Tree2) ) (T (nor Node1 Node2) T) (NIL (= Node1 Node2)) ) ) (co "rt1") (co "rt2") ) )
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#Python
Python
try: from itertools import zip_longest as izip_longest # Python 3.x except: from itertools import izip_longest # Python 2.6+   def fringe(tree): """Yield tree members L-to-R depth first, as if stored in a binary tree""" for node1 in tree: if isinstance(node1, tuple): for node2 in fringe(node1): yield node2 else: yield node1   def same_fringe(tree1, tree2): return all(node1 == node2 for node1, node2 in izip_longest(fringe(tree1), fringe(tree2)))   if __name__ == '__main__': a = 1, 2, 3, 4, 5, 6, 7, 8 b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8)))) c = (((1, 2), 3), 4), 5, 6, 7, 8   x = 1, 2, 3, 4, 5, 6, 7, 8, 9 y = 0, 2, 3, 4, 5, 6, 7, 8 z = 1, 2, (4, 3), 5, 6, 7, 8   assert same_fringe(a, a) assert same_fringe(a, b) assert same_fringe(a, c)   assert not same_fringe(a, x) assert not same_fringe(a, y) assert not same_fringe(a, z)
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#newLISP
newLISP
(set 'upper-bound 1000)   ; The initial sieve is a list of all the numbers starting at 2. (set 'sieve (sequence 2 upper-bound))   ; Keep working until the list is empty. (while sieve   ; The first number in the list is always prime (set 'new-prime (sieve 0)) (println new-prime)   ; Filter the list leaving only the non-multiples of each number. (set 'sieve (filter (lambda (each-number) (not (zero? (% each-number new-prime)))) sieve)))   (exit)
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) The task Calculate the minimum possible size of the initial pile of coconuts collected during the first day. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.) Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). Show your answers here. Extra credit (optional) Give some indication of the number of coconuts each sailor hides during the night. Note Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale! C.f Monkeys and Coconuts - Numberphile (Video) Analytical solution. A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#Raku
Raku
my @ones = flat 'th', 'st', 'nd', 'rd', 'th' xx 6; my @teens = 'th' xx 10; my @suffix = lazy flat (@ones, @teens, @ones xx 8) xx *;   # brute force the first six for 1 .. 6 -> $sailors { for $sailors .. * -> $coconuts { last if check( $sailors, $coconuts ) } }   # finesse 7 through 15 for 7 .. 15 -> $sailors { next if check( $sailors, coconuts( $sailors ) ) }   sub is_valid ( $sailors is copy, $nuts is copy ) { return 0, 0 if $sailors == $nuts == 1; my @shares; for ^$sailors { return () unless $nuts % $sailors == 1; push @shares, ($nuts - 1) div $sailors; $nuts -= (1 + $nuts div $sailors); } push @shares, $nuts div $sailors; return @shares if !?($nuts % $sailors); }   sub check ($sailors, $coconuts) { if my @piles = is_valid($sailors, $coconuts) { say "\nSailors $sailors: Coconuts $coconuts:"; for ^(@piles - 1) -> $k { say "{$k+1}@suffix[$k+1] takes @piles[$k], gives 1 to the monkey." } say "The next morning, each sailor takes @piles[*-1]\nwith none left over for the monkey."; return True; } False; }   multi sub coconuts ( $sailors where { $sailors % 2 == 0 } ) { ($sailors - 1) * ($sailors ** $sailors - 1) } multi sub coconuts ( $sailors where { $sailors % 2 == 1 } ) { $sailors ** $sailors - $sailors + 1 }