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/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#C
C
#include <stdio.h> #include <stdlib.h>   unsigned long long sum35(unsigned long long limit) { unsigned long long sum = 0; for (unsigned long long i = 0; i < limit; i++) if (!(i % 3) || !(i % 5)) sum += i; return sum; }   int main(int argc, char **argv) { unsigned long long limit;   ...
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Befunge
Befunge
" :rebmuN">:#,_&0v |_,#!>#:<"Base: "< <>10g+\00g/:v:p00& v^\p01<%g00:_55+\> >" :muS">:#,_$\.,@
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#C.2B.2B
C++
#include <iostream> #include <numeric> #include <vector>   double add_square(double prev_sum, double new_val) { return prev_sum + new_val*new_val; }   double vec_add_squares(std::vector<double>& v) { return std::accumulate(v.begin(), v.end(), 0.0, add_square); }   int main() { // first, show that for empty vector...
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#Ada
Ada
  with Ada.Command_Line; use Ada.Command_Line; with Ada.Sequential_IO; with Ada.Strings.Maps; use Ada.Strings.Maps; with Ada.Text_IO;   procedure Cipher is package Char_IO is new Ada.Sequential_IO (Character); use Char_IO; Alphabet: constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; ...
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#Arturo
Arturo
key: {:]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\C1yxJ:}   encode: function [str][ bs: new [] loop split str 'ch -> 'bs ++ to :string key\[(to :integer to :char ch)-32] return join bs ]   decode: function [str][ bs: new [] loop split str 'ch -> ...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Babel
Babel
main: { [2 3 5 7 11 13] sp }   sum!  : { <- 0 -> { + } eachar } product!: { <- 1 -> { * } eachar }   sp!: { dup sum %d cr << product %d cr << }   Result: 41 30030
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#BASIC
BASIC
dim array(5) as integer = { 1, 2, 3, 4, 5 }   dim sum as integer = 0 dim prod as integer = 1 for index as integer = lbound(array) to ubound(array) sum += array(index) prod *= array(index) next
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#BQN
BQN
+´÷√⁼1+↕1000 1.6439345666815597
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#Common_Lisp
Common Lisp
(defun f (lst &optional (sum 100) (so-far nil)) "Takes a list of digits as argument" (if (null lst) (cond ((= sum 0) (format t "~d = ~{~@d~}~%" (apply #'+ so-far) (reverse so-far)) 1) (t 0) ) (let ((total 0) (len (length lst)) ) (dotimes (i len total) (let* ((str1 (butlast l...
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#C.23
C#
  using System; using System.Collections.Generic; using System.Numerics;   namespace RosettaCode { class Program { static void Main() { List<BigInteger> candidates = new List<BigInteger>(new BigInteger[] { 1000, 100000, 10000000, 10000000000, 1000000000000000 }); candidat...
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#BQN
BQN
SumDigits ← { 𝕊 𝕩: 10 𝕊 𝕩; 𝕨 𝕊 0: 0; (𝕨|𝕩)+𝕨𝕊⌊𝕩÷𝕨 }   •Show SumDigits 1 •Show SumDigits 1234 •Show 16 SumDigits 254
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Chef
Chef
Sum of squares.   First input is length of vector, then rest of input is vector.   Ingredients. 1 g eggs 0 g bacon   Method. Put bacon into the 1st mixing bowl. Take eggs from refrigerator. Square the eggs. Take bacon from refrigerator. Put bacon into 2nd mixing bowl. Combine bacon into 2nd mixing bowl. Fold bacon into...
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Clojure
Clojure
(defn sum-of-squares [v] (reduce #(+ %1 (* %2 %2)) 0 v))
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#C
C
  #include<stdlib.h> #include<stdio.h> #include<wchar.h>   #define ENCRYPT 0 #define DECRYPT 1 #define ALPHA 33 #define OMEGA 126   int wideStrLen(wchar_t* str){ int i = 0; while(str[i++]!=00);   return i; }   void processFile(char* fileName,char plainKey, char cipherKey,int flag){   FILE* inpFile = fopen(fileName,...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#BASIC256
BASIC256
arraybase 1 dim array(5) array[1] = 1 array[2] = 2 array[3] = 3 array[4] = 4 array[5] = 5   sum = 0 prod = 1 for index = 1 to array[?] sum += array[index] prod *= array[index] next index print "The sum is "; sum #15 print "and the product is "; prod #120 end
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#bc
bc
a[0] = 3.0 a[1] = 1 a[2] = 4.0 a[3] = 1.0 a[4] = 5 a[5] = 9.00 n = 6 p = 1 for (i = 0; i < n; i++) { s += a[i] p *= a[i] } "Sum: "; s "Product: "; p
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Bracmat
Bracmat
( 0:?i & 0:?S & whl'(1+!i:~>1000:?i&!i^-2+!S:?S) & out$!S & out$(flt$(!S,10)) );
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#D
D
import std.stdio;   void main() { import std.algorithm : each, max, reduce, sort; import std.range : take;   Stat stat = new Stat();   comment("Show all solutions that sum to 100"); immutable givenSum = 100; print(givenSum);   comment("Show the sum that has the maximum number of solutions");...
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#C.2B.2B
C++
  #include <iostream>   //-------------------------------------------------------------------------------------------------- typedef unsigned long long bigInt;   using namespace std; //-------------------------------------------------------------------------------------------------- class m35 { public: void doIt( b...
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#C
C
#include <stdio.h>   int SumDigits(unsigned long long n, const int base) { int sum = 0; for (; n; n /= base) sum += n % base; return sum; }   int main() { printf("%d %d %d %d %d\n", SumDigits(1, 10), SumDigits(12345, 10), SumDigits(123045, 10), SumDigits(0xfe, 16), ...
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#CLU
CLU
sum_squares = proc (ns: sequence[int]) returns (int) sum: int := 0 for n: int in sequence[int]$elements(ns) do sum := sum + n ** 2 end return(sum) end sum_squares   start_up = proc () po: stream := stream$primary_output()   stream$putl(po, int$unparse(sum_squares(sequence[int]$[]))) ...
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#CoffeeScript
CoffeeScript
  sumOfSquares = ( list ) -> list.reduce (( sum, x ) -> sum + ( x * x )), 0  
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#C.23
C#
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;   namespace SubstitutionCipherProject { class SubstitutionCipher { static void Main(string[] args) { doEncDec("e:\\source.txt", "enc.txt", true); ...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Befunge
Befunge
0 &>: #v_ $. @ >1- \ & + \v ^ <
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#BQN
BQN
SumProd ← +´⋈×´ +´⋈×´ SumProd 1‿2‿3‿4‿5 ⟨ 15 120 ⟩
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Brat
Brat
p 1.to(1000).reduce 0 { sum, x | sum + 1.0 / x ^ 2 } #Prints 1.6439345666816
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#Delphi
Delphi
defmodule Sum do def to(val) do generate |> Enum.map(&{eval(&1), &1}) |> Enum.filter(fn {v, _s} -> v==val end) |> Enum.each(&IO.inspect &1) end   def max_solve do generate |> Enum.group_by(&eval &1) |> Enum.filter_map(fn {k,_} -> k>=0 end, fn {k,v} -> {length(v),k} end) |> Enum.max...
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Clojure
Clojure
(defn sum-mults [n & mults] (let [pred (apply some-fn (map #(fn [x] (zero? (mod x %))) mults))] (->> (range n) (filter pred) (reduce +))))   (println (sum-mults 1000 3 5))
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#C.23
C#
namespace RosettaCode.SumDigitsOfAnInteger { using System; using System.Collections.Generic; using System.Linq;   internal static class Program { /// <summary> /// Enumerates the digits of a number in a given base. /// </summary> /// <param name="number"> The numb...
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Common_Lisp
Common Lisp
(defun sum-of-squares (vector) (loop for x across vector sum (expt x 2)))
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Cowgol
Cowgol
include "cowgol.coh"; include "argv.coh";   # Sum of squares sub sumsquare(vec: [int32], len: intptr): (out: uint32) is out := 0; while len > 0 loop var cur := [vec]; # make positive first so we can use extra range of uint32 if cur < 0 then cur := -cur; end if; out := out +...
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#C.2B.2B
C++
  #include <iostream> #include <string> #include <fstream>   class cipher { public: bool work( std::string e, std::string f, std::string k ) { if( e.length() < 1 ) return false; fileBuffer = readFile( f ); if( "" == fileBuffer ) return false; keyBuffer = readFile( k ); if( ""...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Bracmat
Bracmat
( ( sumprod = sum prod num . 0:?sum & 1:?prod & (  !arg  :  ? ( #%?num ? & !num+!sum:?sum & !num*!prod:?prod & ~ ) | (!sum.!prod) ) ) & out$sumprod$(2 3 5 7 11 13 17 19) );
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#C
C
/* using pointer arithmetic (because we can, I guess) */ int arg[] = { 1,2,3,4,5 }; int arg_length = sizeof(arg)/sizeof(arg[0]); int *end = arg+arg_length; int sum = 0, prod = 1; int *p;   for (p = arg; p!=end; ++p) { sum += *p; prod *= *p; }
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#C
C
#include <stdio.h>   double Invsqr(double n) { return 1 / (n*n); }   int main (int argc, char *argv[]) { int i, start = 1, end = 1000; double sum = 0.0;   for( i = start; i <= end; i++) sum += Invsqr((double)i);   printf("%16.14f\n", sum);   return 0; }
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#Elixir
Elixir
defmodule Sum do def to(val) do generate |> Enum.map(&{eval(&1), &1}) |> Enum.filter(fn {v, _s} -> v==val end) |> Enum.each(&IO.inspect &1) end   def max_solve do generate |> Enum.group_by(&eval &1) |> Enum.filter_map(fn {k,_} -> k>=0 end, fn {k,v} -> {length(v),k} end) |> Enum.max...
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#COBOL
COBOL
  Identification division. Program-id. three-five-sum.   Data division. Working-storage section. 01 ws-the-limit pic 9(18) value 1000. 01 ws-the-number pic 9(18). 01 ws-the-sum pic 9(18). 01 ws-sum-out pic z(18).   Procedure division. Main-program. Perform Do-sum varying ws-the-number from 1 by 1 ...
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#C.2B.2B
C++
#include <iostream> #include <cmath> int SumDigits(const unsigned long long int digits, const int BASE = 10) { int sum = 0; unsigned long long int x = digits; for (int i = log(digits)/log(BASE); i>0; i--){ const double z = std::pow(BASE,i); const unsigned long long int t = x/z; sum += t; x ...
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Crystal
Crystal
  def sum_squares(a) a.map{|e| e*e}.sum() end   puts sum_squares([1, 2, 3]) # => 14  
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#D
D
T sumSquares(T)(T[] a) pure nothrow @safe @nogc { T sum = 0; foreach (e; a) sum += e ^^ 2; return sum; }   void main() { import std.stdio: writeln;   [3.1, 1.0, 4.0, 1.0, 5.0, 9.0].sumSquares.writeln; }
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#11l
11l
print(‘knight’[1..]) print(‘socks’[0 .< (len)-1]) print(‘brooms’[1 .< (len)-1])
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#11l
11l
Deque[Int] s V seed = 292929   s.append(seed) s.append(1)   L(n) 2..54 s.append((s[n - 2] - s[n - 1]) % 10 ^ 9)   Deque[Int] r L(n) 55 V i = (34 * (n + 1)) % 55 r.append(s[i])   F py_mod(a, b) R ((a % b) + b) % b   F getnextr()  :r.append(py_mod((:r[0] - :r[31]), 10 ^ 9))  :r.pop_left() R :r[54]   L ...
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#D
D
import std.stdio; import std.string; import std.traits;   string text = `Here we have to do is there will be a input/source file in which we are going to Encrypt the file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it int...
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#Factor
Factor
USING: assocs combinators combinators.short-circuit command-line hashtables io io.encodings.utf8 io.files kernel math.order multiline namespaces qw sequences ; IN: rosetta-code.substitution-cipher   CONSTANT: alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"   CONSTANT: default-key "VsciBjedgrzyHa...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#C.23
C#
int sum = 0, prod = 1; int[] arg = { 1, 2, 3, 4, 5 }; foreach (int value in arg) { sum += value; prod *= value; }
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#C.23
C#
class Program { static void Main(string[] args) { // Create and fill a list of number 1 to 1000   List<double> myList = new List<double>(); for (double i = 1; i < 1001; i++) { myList.Add(i); } // Calculate the sum of 1/x^2   var sum = myList.Su...
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#F.23
F#
  (* Generate the data set Nigel Galloway February 22nd., 2017 *) type N = {n:string; g:int} let N = seq { let rec fn n i g e l = seq { match i with |9 -> yield {n=l + "-9"; g=g+e-9} yield {n=l + "+9"; g=g+e+9} yield {n=l + "9"; g=g+e*10+9*n} |_ -> yield! fn -1 (i+1) (g+e) -i (l + str...
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Common_Lisp
Common Lisp
(defun sum-3-5-slow (limit) (loop for x below limit when (or (zerop (rem x 3)) (zerop (rem x 5))) sum x))
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Clojure
Clojure
(defn sum-digits [n base] (let [number (if-not (string? n) (Long/toString n base) n)] (reduce + (map #(Long/valueOf (str %) base) number))))
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Dart
Dart
sumOfSquares(list) { var sum=0; list.forEach((var n) { sum+=(n*n); }); return sum; }   main() { print(sumOfSquares([])); print(sumOfSquares([1,2,3])); print(sumOfSquares([10])); }
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#360_Assembly
360 Assembly
* Substring/Top and tail 04/03/2017 SUBSTRTT CSECT USING SUBSTRTT,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST...
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#ACL2
ACL2
(defun str-rest (str) (coerce (rest (coerce str 'list)) 'string))   (defun rdc (xs) (if (endp (rest xs)) nil (cons (first xs) (rdc (rest xs)))))   (defun str-rdc (str) (coerce (rdc (coerce str 'list)) 'string))   (str-rdc "string") (str-rest "string") (str-rest (str-rdc "string"))
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Ada
Ada
package Subtractive_Generator is type State is private; procedure Initialize (Generator : in out State; Seed : Natural); procedure Next (Generator : in out State; N : out Natural); private type Number_Array is array (Natural range <>) of Natural; type State is record R  : Number_Array (0 .. 54); ...
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#Fortran
Fortran
program substitution implicit none   integer, parameter :: len_max = 256 integer, parameter :: eof = -1 integer :: in_unit = 9, out_unit = 10, ios character(len_max) :: line   open(in_unit, file="plain.txt", iostat=ios) if (ios /= 0) then write(*,*) "Error opening plain.txt file" stop end if   ...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#C.2B.2B
C++
#include <numeric> #include <functional>   int arg[] = { 1, 2, 3, 4, 5 }; int sum = std::accumulate(arg, arg+5, 0, std::plus<int>()); // or just // std::accumulate(arg, arg + 5, 0); // since plus() is the default functor for accumulate int prod = std::accumulate(arg, arg+5, 1, std::multiplies<int>());
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#C.2B.2B
C++
#include <iostream>   double f(double x);   int main() { unsigned int start = 1; unsigned int end = 1000; double sum = 0;   for( unsigned int x = start; x <= end; ++x ) { sum += f(x); } std::cout << "Sum of f(x) from " << start << " to " << end << " is " << sum << std::endl; retu...
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#Forth
Forth
CREATE *OPS CHAR + C, CHAR - C, CHAR # C, CREATE 0OPS CHAR - C, CHAR # C, CREATE BUFF 43 C, 43 CHARS ALLOT CREATE PTR CELL ALLOT CREATE LIMITS 2 C, 3 C, 3 C, 3 C, 3 C, 3 C, 3 C, 3 C, 3 C, CREATE INDX 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, CREATE OPS 0OPS , *OPS , *OPS , *OPS , *OPS , *OPS , *OPS , *OPS , *OPS ,...
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Component_Pascal
Component Pascal
  MODULE Sum3_5; IMPORT StdLog, Strings, Args;   PROCEDURE DoSum(n: INTEGER):INTEGER; VAR i,sum: INTEGER; BEGIN sum := 0;i := 0; WHILE (i < n) DO IF (i MOD 3 = 0) OR (i MOD 5 = 0) THEN INC(sum,i) END; INC(i) END; RETURN sum END DoSum;   PROCEDURE Compute*; VAR params: Args.Params; i,n,res: INTEGER; BEGIN A...
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Common_Lisp
Common Lisp
(defun sum-digits (number base) (loop for n = number then q for (q r) = (multiple-value-list (truncate n base)) sum r until (zerop q)))
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Delphi
Delphi
program SumOfSq;   {$APPTYPE CONSOLE}   uses Math;   type TDblArray = array of Double;   var A: TDblArray;   begin Writeln(SumOfSquares([]):6:2); // 0.00 Writeln(SumOfSquares([1, 2, 3, 4]):6:2); // 30.00 A:= nil; Writeln(SumOfSquares(A):6:2); // 0.00 A:= TDblArray.Create(1, 2, 3,...
http://rosettacode.org/wiki/Successive_prime_differences
Successive prime differences
The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ... The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values. Example 1: Specifying that the difference between s'primes be 2 leads to the groups: ...
#11l
11l
F primes_upto(limit) V is_prime = [0B] * 2 [+] [1B] * (limit - 1) L(n) 0 .< Int(limit ^ 0.5 + 1.5) I is_prime[n] L(i) (n * n .< limit + 1).step(n) is_prime[i] = 0B R enumerate(is_prime).filter((i, prime) -> prime).map((i, prime) -> i)   F successive_primes(primes, diffs) [[Int]] r...
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Action.21
Action!
PROC Main() CHAR ARRAY text="qwertyuiop" CHAR ARRAY res(20) BYTE n,m   PrintF("Original string:%E ""%S""%E%E",text)   SCopyS(res,text,2,text(0)) PrintF("String without the top:%E ""%S""%E%E",res)   SCopyS(res,text,1,text(0)-1) PrintF("String without the tail:%E ""%S""%E%E",res)   SCopyS(res,text,2,...
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Ada
Ada
with Ada.Text_IO;   procedure Remove_Characters is S: String := "upraisers"; use Ada.Text_IO; begin Put_Line("Full String: """ & S & """"); Put_Line("Without_First: """ & S(S'First+1 .. S'Last) & """"); Put_Line("Without_Last: """ & S(S'First .. S'Last-1) & """"); Put_Line("Without_Both: """ & S...
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#AutoHotkey
AutoHotkey
r := InitR(292929)   Loop, 10 Out .= (A_Index + 219) ":`t" GetRand(r) "`n"   MsgBox, % Out   GetRand(r) { i := Mod(r["j"], 55) , r[i] := Mod(r[i] - r[Mod(i + 31, 55)], r["m"]) , r["j"] += 1 return, (r[i] < 0 ? r[i] + r["m"] : r[i]) }   InitR(Seed) { r := {"j": 0, "m": 10 ** 9}, s := {0: Seed, 1: 1} Loop, 53 s[...
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' uses same alphabet and key as Ada language example Const string1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Const string2 = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"   Sub process(inputFile As String, outputFile As String, encrypt As Boolean) Open inputFile For Input ...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Chef
Chef
Sum and Product of Numbers as a Piece of Cake.   This recipe sums N given numbers.   Ingredients. 1 N 0 sum 1 product 1 number   Method. Put sum into 1st mixing bowl. Put product into 2nd mixing bowl. Take N from refrigerator. Chop N. Take number from refrigerator. Add number into 1st mixing bowl. Combine number into 2...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Clean
Clean
array = {1, 2, 3, 4, 5} Sum = sum [x \\ x <-: array] Prod = foldl (*) 1 [x \\ x <-: array]
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#CLIPS
CLIPS
(deffunction S (?x) (/ 1 (* ?x ?x))) (deffunction partial-sum-S (?start ?stop) (bind ?sum 0) (loop-for-count (?i ?start ?stop) do (bind ?sum (+ ?sum (S ?i))) ) (return ?sum) )
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#Fortran
Fortran
C ROSSETACODE: SUM TO 100, FORTRAN IV C FIND SOLUTIONS TO THE "SUM TO ONE HUNDRED" PUZZLE C ================================================= PROGRAM SUMTO100 DATA NEXPRM1/13121/ WRITE(6,110) 110 FORMAT(1X/1X,34HSHOW ALL SOLUTIONS THAT SUM TO 100/) DO 10 I = 0,NEXPRM1 10 IF ( IEVAL(I) .EQ....
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Cowgol
Cowgol
include "cowgol.coh";   # sum multiples up to given input interface SumMulTo(mul: uint32, to: uint32): (rslt: uint32);   # naive implementation sub naiveSumMulTo implements SumMulTo is rslt := 0; var cur := mul; while cur < to loop rslt := rslt + cur; cur := cur + mul; end loop; end sub;...
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Cowgol
Cowgol
include "cowgol.coh";   sub digitSum(n: uint32, base: uint32): (r: uint32) is r := 0; while n > 0 loop r := r + n % base; n := n / base; end loop; end sub;   print_i32(digitSum(1, 10)); # prints 1 print_nl(); print_i32(digitSum(1234, 10)); # prints 10 print_nl(); print_i32(digitSum(0xFE, 16)...
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Draco
Draco
proc nonrec sum_squares([*] int arr) ulong: ulong sum, item; word i, len; sum := 0; len := dim(arr,1); if len>0 then for i from 0 upto len-1 do item := |arr[i]; sum := sum + item * item od fi; sum corp   proc nonrec main() void: type A0 = [0] int,...
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#E
E
def sumOfSquares(numbers) { var sum := 0 for x in numbers { sum += x**2 } return sum }
http://rosettacode.org/wiki/Successive_prime_differences
Successive prime differences
The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ... The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values. Example 1: Specifying that the difference between s'primes be 2 leads to the groups: ...
#ALGOL_68
ALGOL 68
BEGIN # find some sequences of primes where the gaps between the elements # # follow specific patterns # # reurns a list of primes up to n # PROC prime list = ( INT n )[]INT: BEGIN # sieve the primes to n # INT no = 0, yes = 1; ...
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Aime
Aime
o_text(delete("knights", 0)); o_newline(); o_text(delete("knights", -1)); o_newline(); o_text(delete(delete("knights", 0), -1)); o_newline();
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#BBC_BASIC
BBC BASIC
dummy% = FNsubrand(292929) FOR i% = 1 TO 10 PRINT FNsubrand(0) NEXT END   DEF FNsubrand(s%) PRIVATE r%(), p% : DIM r%(54) IF s% = 0 THEN p% = (p% + 1) MOD 55 r%(p%) = r%(p%) - r%((p% + 31) MOD 55) IF r%(p%) < 0 r%(p%) += 10^9 = r%(p%) ...
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#Go
Go
package main   import ( "fmt" "strings" )   var key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"   func encode(s string) string { bs := []byte(s) for i := 0; i < len(bs); i++ { bs[i] = key[int(bs[i]) - 32] } return string(bs) } ...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Clojure
Clojure
(defn sum [vals] (reduce + vals))   (defn product [vals] (reduce * vals))
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#CLU
CLU
sum_and_product = proc (a: array[int]) returns (int,int) signals (overflow) sum: int := 0 prod: int := 1 for i: int in array[int]$elements(a) do sum := sum + i prod := prod * i end resignal overflow return(sum, prod) end sum_and_product   start_up = proc () arr: array[int] := arr...
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Clojure
Clojure
(reduce + (map #(/ 1.0 % %) (range 1 1001)))
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#FreeBASIC
FreeBASIC
  #define PERM 13122   'Between any two adjacent digits there can be nothing, a plus, or a minus. 'And the first term can only be + or - 'This is equivalent to an eight-digit base 3 number. We therefore only need 'to consider 2*3^8=13122 possibilities   function ndig(n as uinteger) as uinteger return 1+int(log(n+0....
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Crystal
Crystal
def sum_3_5_multiples(n) (0...n).select { |i| i % 3 == 0 || i % 5 == 0 }.sum end   puts sum_3_5_multiples(1000)
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Crystal
Crystal
class String def sum_digits(base : Int) : Int32 self.chars.reduce(0) { |acc, c| value = c.to_i(base) acc += value } end end   puts("1".sum_digits 10) puts("1234".sum_digits 10) puts("fe".sum_digits 16) puts("f0e".sum_digits 16)
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Eiffel
Eiffel
  class APPLICATION   create make   feature -- Initialization   make local a: ARRAY [INTEGER] do a := <<1, -2, 3>> print ("%NSquare sum of <<1, 2, 3>>: " + sum_of_square (a).out)   a := <<>> print ("%NSquare sum of <<>>: " + sum_of_square (a).out) end   feature -- Access   sum_of_square (a: ITE...
http://rosettacode.org/wiki/Successive_prime_differences
Successive prime differences
The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ... The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values. Example 1: Specifying that the difference between s'primes be 2 leads to the groups: ...
#Arturo
Arturo
LIM: 1000000   findDiffs: function [r][ if r=[1] -> return [[2 3]] i: 3 tupled: map 0..dec size r 'x -> fold slice r 0 x [a b][a+b] diffs: new [] while [i < LIM][ if prime? i [ prset: map tupled 't -> i + t if every? prset 'elem -> prime? elem [ 'diffs...
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   STRING str="upraisers"; printf(($gl$, str, # remove no characters # str[LWB str+1: ], # remove the first character # str[ :UPB str-1], # remove the last character # str[LWB str+1:UPB str-1], # remove both the first and last character # st...
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Bracmat
Bracmat
1000000000:?MOD; tbl$(state,55); 0:?si:?sj;   (subrand-seed= i,j,p2 . 1:?p2 & mod$(!arg,!MOD):?(0$?state) & 1:?i & 21:?j & whl ' ( !i:<55 & (!j:~<55&!j+-55:?j|) & !p2:?(!j$?state) & (  !arg+-1*!p2:?p2:<0 & !p2+!MOD:?p2 | ) & !(!j$state):?arg & !...
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#C
C
#include<stdio.h>   #define MOD 1000000000 int state[55], si = 0, sj = 0;   int subrand();   void subrand_seed(int p1) { int i, j, p2 = 1;   state[0] = p1 % MOD; for (i = 1, j = 21; i < 55; i++, j += 21) { if (j >= 55) j -= 55; state[j] = p2; if ((p2 = p1 - p2) < 0) p2 += MOD; p1 = state[j]; } si = 0; sj ...
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#IS-BASIC
IS-BASIC
100 PROGRAM "SuChiper.bas" 110 STRING ST$(1 TO 2)*52,K$*1 120 LET ST$(1)="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 130 LET ST$(2)="VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN" 140 CLEAR SCREEN:PRINT "1 - encode, 2 - decode" 150 DO 160 LET K$=INKEY$ 170 LOOP UNTIL K$="1" OR K$="2" 180 IF K$="1" T...
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#Haskell
Haskell
import Data.Char (chr) import Data.Maybe (fromMaybe) import Data.Tuple (swap) import System.Environment (getArgs)   data Command = Cipher String | Decipher String | Invalid   alphabet :: String alphabet = chr <$> [32..126]   cipherMap :: [(Char, Char)] cipherMap = zip alphabet (shuffle 20 alpha...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. array-sum-and-product.   DATA DIVISION. WORKING-STORAGE SECTION. 78 Array-Size VALUE 10. 01 array-area VALUE "01020304050607080910". 03 array PIC 99 OCCURS Array-Size TIMES.   01 ...
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#CLU
CLU
series_sum = proc (from, to: int, fn: proctype (real) returns (real)) returns (real) sum: real := 0.0 for i: int in int$from_to(from, to) do sum := sum + fn(real$i2r(i)) end return(sum) end series_sum   one_over_k_squared = proc (k: real) returns (real) retur...
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#Frink
Frink
  digits = array[1 to 9] opList = makeArray[[8], ["", " + ", " - "]] opList.pushFirst[["", "-"]] countDict = new dict   multifor ops = opList { str = "" for d = rangeOf[digits] str = str + ops@d + digits@d e = eval[str] countDict.increment[e, 1] if e == 100 println[str] } println[]   // Find ...
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#D
D
import std.stdio, std.bigint;   BigInt sum35(in BigInt n) pure nothrow { static BigInt sumMul(in BigInt n, in int f) pure nothrow { immutable n1 = (f==n?n:(n - 1) ) / f; return f * n1 * (n1 + 1) / 2; }   return sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15); }   void main() { 1.BigInt.sum35...
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#D
D
import std.stdio, std.bigint;   uint sumDigits(T)(T n, in uint base=10) pure nothrow in { assert(base > 1); } body { typeof(return) total = 0; for ( ; n; n /= base) total += n % base; return total; }   void main() { 1.sumDigits.writeln; 1_234.sumDigits.writeln; sumDigits(0xfe, 16).wr...
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Elena
Elena
import system'routines; import extensions;   SumOfSquares(list) = list.selectBy:(x => x * x).summarize(new Integer());   public program() { console .printLine(SumOfSquares(new int[]{4, 8, 15, 16, 23, 42})) .printLine(SumOfSquares(new int[]{1, 2, 3, 4, 5})) .printLine(SumOfSquares(Array....
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Elixir
Elixir
iex(1)> Enum.reduce([3,1,4,1,5,9], 0, fn x,sum -> sum + x*x end) 133
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#11l
11l
T Sudoku solved = 0B grid = [0] * 81   F (rows) assert(rows.len == 9 & all(rows.map(row -> row.len == 9)), ‘Grid must be 9 x 9’) L(i) 9 L(j) 9 .grid[9 * i + j] = Int(rows[i][j])   F solve() print("Starting grid:\n\n"(.)) .placeNumber(0) print(I .solved {"So...
http://rosettacode.org/wiki/Successive_prime_differences
Successive prime differences
The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ... The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values. Example 1: Specifying that the difference between s'primes be 2 leads to the groups: ...
#AWK
AWK
  # syntax: GAWK -f SUCCESSIVE_PRIME_DIFFERENCES.AWK BEGIN { for (i=lo=0; i<=hi=1000000; i++) { if (is_prime(i)) { p_arr[++p] = i } } printf("there are %d primes between %d - %d\n",p,lo,hi) fmt = "%-11s %5s %-15s %s\n" printf(fmt,"differences","count","first group","last group") ...
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Amazing_Hopper
Amazing Hopper
  #include <hopper.h> #proto showmessage(_X_) main: s="message", t=s ++s, _show message(s) s=t --s, _show message(s) ++s, _show message(s) {0}return   .locals showmessage(_S_) {_S_,"\n"}print back