! Find the sum of multiples of two factors below a limit -
! Project Euler problem 1: multiples of 3 or 5 below 1000 & 10**20;
BEGIN
    INTEGER PROCEDURE GCD(a, b); INTEGER a, b;
        GCD := IF b = 0 THEN a ELSE GCD(b, MOD(a, b));

    ! sum of multiples of n up to limit;
    INTEGER PROCEDURE multiples(n, limit); INTEGER n, limit;
    BEGIN
        INTEGER m;
        m := limit // n;
    ! moving //2 to sumMultiples() looked just too silly    ;
        multiples := n*((m*(m+1)) // 2) ! and risks overflow;
    END
    ! sum of multiples of n or m below limit;
    INTEGER PROCEDURE sumMultiples(n, m, limit);
        INTEGER n, m, limit;
    BEGIN
        INTEGER LCM;
        LCM:= (n // GCD(n, m)) * m;
        limit := limit-1;
        sumMultiples := multiples(n, limit) + multiples(m, limit)
                        - multiples(LCM, limit)
    END sumMultiples;

    ! Extra creditable: math is about avoiding calculation tedium;
    TEXT PROCEDURE repeat(c, n); CHARACTER c; INTEGER n; BEGIN
        TEXT r; r :- BLANKS(n);
        FOR n := n STEP -1 UNTIL 1 DO r.PUTCHAR(c);
        repeat :- r;
    END;
    TEXT PROCEDURE sumOfMultiplesOf3or5below10toThePowerOf(e);
        INTEGER e;
    sumOfMultiplesOf3or5below10toThePowerOf :-
        IF e < 1 THEN "0" ELSE IF e = 1 THEN "23"
        ELSE "23" & repeat('3', e-2)
            & "1" & repeat('6', e-2) & "8";

    INTEGER factor, n;
    FOR factor := 5 !, 2, 6;
                    DO BEGIN
        OUTTEXT("sum of positive multiples of 3 and");
        OUTINT(factor, 2); OUTCHAR(':');
        FOR n := ! 1 STEP 1 UNTIL 15, 100,;
                 1000 DO BEGIN
            OUTCHAR(' '); OUTINT(sumMultiples(3, factor, n), 0)
        END;
        OUTIMAGE
    END;
    FOR n := 0, 1, 3, 5, 10, 20, 40 DO BEGIN
        OUTTEXT(sumOfMultiplesOf3or5below10toThePowerOf(n));
        OUTIMAGE
    END
END


import Data.List (intersect)

s1, s2, s3, s4 :: [(Int, Int)]
s1 = [(x, y) | x <- [1 .. 100], y <- [1 .. 100], 1 < x && x < y && x + y < 100]

add, mul :: (Int, Int) -> Int
add (x, y) = x + y
mul (x, y) = x * y

sumEq, mulEq :: (Int, Int) -> [(Int, Int)]
sumEq p = filter (\q -> add q == add p) s1
mulEq p = filter (\q -> mul q == mul p) s1

s2 = filter (\p -> all (\q -> (length $ mulEq q) /= 1) (sumEq p)) s1
s3 = filter (\p -> length (mulEq p `intersect` s2) == 1) s2
s4 = filter (\p -> length (sumEq p `intersect` s3) == 1) s3

main = print s4


package org.rosettacode;

import java.util.ArrayList;
import java.util.List;

/**
 * This program applies the logic in the Sum and Product Puzzle for the value
 * provided by systematically applying each requirement to all number pairs in
 * range. Note that the requirements: (x, y different), (x < y), and
 * (x, y > MIN_VALUE) are baked into the loops in run(), sumAddends(), and
 * productFactors(), so do not need a separate test. Also note that to test a
 * solution to this logic puzzle, it is suggested to test the condition with
 * maxSum = 1685 to ensure that both the original solution (4, 13) and the
 * additional solution (4, 61), and only these solutions, are found. Note
 * also that at 1684 only the original solution should be found!
 */
public class SumAndProductPuzzle {
    private final long beginning;
    private final int maxSum;
    private static final int MIN_VALUE = 2;
    private List<int[]> firstConditionExcludes = new ArrayList<>();
    private List<int[]> secondConditionExcludes = new ArrayList<>();

    public static void main(String... args){

        if (args.length == 0){
            new SumAndProductPuzzle(100).run();
            new SumAndProductPuzzle(1684).run();
            new SumAndProductPuzzle(1685).run();
        } else {
            for (String arg : args){
                try{
                    new SumAndProductPuzzle(Integer.valueOf(arg)).run();
                } catch (NumberFormatException e){
                    System.out.println("Please provide only integer arguments. " +
                            "Provided argument " + arg + " was not an integer. " +
                            "Alternatively, calling the program with no arguments " +
                            "will run the puzzle where maximum sum equals 100, 1684, and 1865.");
                }
            }
        }
    }

    public SumAndProductPuzzle(int maxSum){
        this.beginning = System.currentTimeMillis();
        this.maxSum = maxSum;
        System.out.println("Run with maximum sum of " + String.valueOf(maxSum) +
                " started at " + String.valueOf(beginning) + ".");
    }

    public void run(){
        for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){
            for (int y = x + 1; y < maxSum - MIN_VALUE; y++){

                if (isSumNoGreaterThanMax(x,y) &&
                    isSKnowsPCannotKnow(x,y) &&
                    isPKnowsNow(x,y) &&
                    isSKnowsNow(x,y)
                    ){
                    System.out.println("Found solution x is " + String.valueOf(x) + " y is " + String.valueOf(y) +
                            " in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms.");
                }
            }
        }
        System.out.println("Run with maximum sum of " + String.valueOf(maxSum) +
                " ended in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms.");
    }

    public boolean isSumNoGreaterThanMax(int x, int y){
        return x + y <= maxSum;
    }

    public boolean isSKnowsPCannotKnow(int x, int y){

        if (firstConditionExcludes.contains(new int[] {x, y})){
            return false;
        }

        for (int[] addends : sumAddends(x, y)){
            if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {
                firstConditionExcludes.add(new int[] {x, y});
                return false;
            }
        }
        return true;
    }

    public boolean isPKnowsNow(int x, int y){

        if (secondConditionExcludes.contains(new int[] {x, y})){
            return false;
        }

        int countSolutions = 0;
        for (int[] factors : productFactors(x, y)){
            if (isSKnowsPCannotKnow(factors[0], factors[1])){
                countSolutions++;
            }
        }

        if (countSolutions == 1){
            return true;
        } else {
            secondConditionExcludes.add(new int[] {x, y});
            return false;
        }
    }

    public boolean isSKnowsNow(int x, int y){

        int countSolutions = 0;
        for (int[] addends : sumAddends(x, y)){
            if (isPKnowsNow(addends[0], addends[1])){
                countSolutions++;
            }
        }
        return countSolutions == 1;
    }

    public List<int[]> sumAddends(int x, int y){

        List<int[]> list = new ArrayList<>();
        int sum = x + y;

        for (int addend = MIN_VALUE; addend < sum - addend; addend++){
            if (isSumNoGreaterThanMax(addend, sum - addend)){
                list.add(new int[]{addend, sum - addend});
            }
        }
        return list;
    }

    public List<int[]> productFactors(int x, int y){

        List<int[]> list = new ArrayList<>();
        int product = x * y;

        for (int factor = MIN_VALUE; factor < product / factor; factor++){
            if (product % factor == 0){
                if (isSumNoGreaterThanMax(factor, product / factor)){
                    list.add(new int[]{factor, product / factor});
                }
            }
        }
        return list;
    }
}


  [ $ "bigrat.qky" loadfile ] now!

  [ 0 n->v rot times
      [ i^ 1+ 2 ** n->v 1/v v+ ] ] is sots ( n --> n/d )

  1000 sots
  2dup
  proper 1000000 round improper

  say "Sum of the series to n=1000."
  cr cr
  say "As a proper fraction, best approximation where the denominator does not exceed 1 million."
  cr cr
  proper$ echo$ say " (Correct to ten places after the decimal point.)"
  cr cr
  say "As a decimal fraction, first 1000 places after the decimal point."
  cr cr
  1000 point$ echo$


#lang typed/racket

(: S : Natural -> Real)
(define (S n)
  (for/sum: : Real ([k : Natural (in-range 1 (+ n 1))])
    (/ 1.0 (* k k))))


#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>());


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 2nd mixing bowl.
Chop N until choped.
Pour contents of 2nd mixing bowl into the baking dish.
Pour contents of 1st mixing bowl into the baking dish.

Serves 1.


array = {1, 2, 3, 4, 5}
Sum = sum [x \\ x <-: array]
Prod = foldl (*) 1 [x \\ x <-: array]


clear all
set obs 999
gen a=_n
tabstat a if mod(a,3)==0 | mod(a,5)==0, statistic(sum)


var n:Int=1000

func sum(x:Int)->Int{

	var s:Int=0
	for i in 0...x{
		if i%3==0 || i%5==0
		{
			s=s+i
		}

	}
	return s
}

var sumofmult:Int=sum(x:n)
print(sumofmult)


# Fairly simple version; only counts by 3 and 5, skipping intermediates
proc mul35sum {n} {
    for {set total [set threes [set fives 0]]} {$threes<$n||$fives<$n} {} {
	if {$threes<$fives} {
	    incr total $threes
	    incr threes 3
	} elseif {$threes>$fives} {
	    incr total $fives
	    incr fives 5
	} else {
	    incr total $threes
	    incr threes 3
	    incr fives 5
	}
    }
    return $total
}


(function () {
    'use strict';

    // GENERIC FUNCTIONS

    // concatMap :: (a -> [b]) -> [a] -> [b]
    var concatMap = function concatMap(f, xs) {
            return [].concat.apply([], xs.map(f));
        },

        // curry :: ((a, b) -> c) -> a -> b -> c
        curry = function curry(f) {
            return function (a) {
                return function (b) {
                    return f(a, b);
                };
            };
        },

        // intersectBy :: (a - > a - > Bool) - > [a] - > [a] - > [a]
        intersectBy = function intersectBy(eq, xs, ys) {
            return xs.length && ys.length ? xs.filter(function (x) {
                return ys.some(curry(eq)(x));
            }) : [];
        },

        // range :: Int -> Int -> Maybe Int -> [Int]
        range = function range(m, n, step) {
            var d = (step || 1) * (n >= m ? 1 : -1);
            return Array.from({
                length: Math.floor((n - m) / d) + 1
            }, function (_, i) {
                return m + i * d;
            });
        };

    // PROBLEM FUNCTIONS

    // add, mul :: (Int, Int) -> Int
    var add = function add(xy) {
            return xy[0] + xy[1];
        },
        mul = function mul(xy) {
            return xy[0] * xy[1];
        };

    // sumEq, mulEq :: (Int, Int) -> [(Int, Int)]
    var sumEq = function sumEq(p) {
            var addP = add(p);
            return s1.filter(function (q) {
                return add(q) === addP;
            });
        },
        mulEq = function mulEq(p) {
            var mulP = mul(p);
            return s1.filter(function (q) {
                return mul(q) === mulP;
            });
        };

    // pairEQ :: ((a, a) -> (a, a)) -> Bool
    var pairEQ = function pairEQ(a, b) {
        return a[0] === b[0] && a[1] === b[1];
    };

    // MAIN

    // xs :: [Int]
    var xs = range(1, 100);

    // s1 s2, s3, s4 :: [(Int, Int)]
    var s1 = concatMap(function (x) {
            return concatMap(function (y) {
                return 1 < x && x < y && x + y < 100 ? [
                    [x, y]
                ] : [];
            }, xs);
        }, xs),

        s2 = s1.filter(function (p) {
            return sumEq(p).every(function (q) {
                return mulEq(q).length > 1;
            });
        }),

        s3 = s2.filter(function (p) {
            return intersectBy(pairEQ, mulEq(p), s2).length === 1;
        }),

        s4 = s3.filter(function (p) {
            return intersectBy(pairEQ, sumEq(p), s3).length === 1;
        });

    return s4;
})();


0 1 1000 1 range each 1.0 swap dup * / +
"%g\n" print


Red []
s: 0
repeat n 1000 [  s:   1.0 / n ** 2  + s  ]
print s


(defn sum [vals] (reduce + vals))

(defn product [vals] (reduce * vals))


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] := array[int]$[1,2,3,4,5,6,7,8,9,10]
    sum, prod: int := sum_and_product(arr)

    po: stream := stream$primary_output()
    stream$putl(po, "Sum = " || int$unparse(sum))
    stream$putl(po, "Product = " || int$unparse(prod))
end start_up


       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  array-sum               PIC 9(8).
       01  array-product           PIC 9(10) VALUE 1.

       01  i                       PIC 99.

       PROCEDURE DIVISION.
           PERFORM VARYING i FROM 1 BY 1 UNTIL Array-Size < i
               ADD array (i) TO array-sum
               MULTIPLY array (i) BY array-product
           END-PERFORM

           DISPLAY "Sum:     " array-sum
           DISPLAY "Product: " array-product

           GOBACK
           .


function sum_multiples {
  typeset -i n=$1 limit=$2
  typeset -i max=limit-1
  (( max -= max % n ))
  printf '%d\n' $(( max / n * (n+max)/2 ))
}

function sum35 {
  typeset -i limit=$1
  printf '%d\n' $((  $(sum_multiples  3 $limit)
                   + $(sum_multiples  5 $limit)
                   - $(sum_multiples 15 $limit) ))
}

for (( l=1; l<=1000000000; l*=10 )); do
  printf '%10d\t%18d\n' "$l" "$(sum35 "$l")"
done


Private Function SumMult3and5VBScript(n As Double) As Double
Dim i As Double
    For i = 1 To n - 1
        If i Mod 3 = 0 Or i Mod 5 = 0 Then
            SumMult3and5VBScript = SumMult3and5VBScript + i
        End If
    Next
End Function


Function multsum35(n)
	For i = 1 To n - 1
		If i Mod 3 = 0 Or i Mod 5 = 0 Then
			multsum35 = multsum35 + i
		End If
	Next
End Function

WScript.StdOut.Write multsum35(CLng(WScript.Arguments(0)))
WScript.StdOut.WriteLine


# For readability:
def collect(c): map(select(c));

# stream-oriented checks:
def hasMoreThanOne(s): [limit(2;s)] | length > 1;

def hasOne(s): [limit(2;s)] | length == 1;

def prod: .[0] * .[1];

## A stream of admissible [x,y] values
def xy:
  [range(2;50) as $x  # 1 < X < Y < 100
   | range($x+1; 101-$x) as $y
   | [$x, $y] ] ;

# The stream of [x,y] pairs matching "S knows the sum is $sum"
def sumEq($sum): select( $sum == add );

# The stream of [x,y] pairs matching "P knows the product is $prod"
def prodEq($p): select( $p == prod );

## The solver:
def solve:
  xy as $s0

# S says P does not know:
  | $s0
  | collect(add as $sum
      | all( $s0[]|sumEq($sum);
             prod as $p
             | hasMoreThanOne($s0[] | prodEq($p)))) as $s1

# P says: Now I know:
  | $s1
  | collect(prod as $prod | hasOne( $s1[]|prodEq($prod)) ) as $s2

# S says: Now I also know
  | $s2[]
  | select(add as $sum | hasOne( $s2[] | sumEq($sum)) ) ;

solve


using Primes

function satisfy1(x::Integer)
    prmslt100 = primes(100)
    for i in 2:(x ÷ 2)
        if i ∈ prmslt100 && x - i ∈ prmslt100
            return false
        end
    end
    return true
end

function satisfy2(x::Integer)
    once = false
    for i in 2:isqrt(x)
        if x % i == 0
            j = x ÷ i
            if 2 < j < 100 && satisfy1(i + j)
                if once return false end
                once = true
            end
        end
    end
    return once
end

function satisfyboth(x::Integer)
    if !satisfy1(x) return 0 end
    found = 0
    for i in 2:(x ÷ 2)
        if satisfy2(i * (x - i))
            if found > 0 return 0 end
            found = i
        end
    end
    return found
end

for i in 2:99
    if (j = satisfyboth(i)) > 0
        println("Solution: ($j, $(i - j))")
    end
end


// version 1.1.4-3

data class P(val x: Int, val y: Int, val sum: Int, val prod: Int)

fun main(args: Array<String>) {
    val candidates = mutableListOf<P>()
    for (x in 2..49) {
        for (y in x + 1..100 - x) {
            candidates.add(P(x, y, x + y, x * y))
        }
    }

    val sums = candidates.groupBy { it.sum }
    val prods = candidates.groupBy { it.prod }

    val fact1 = candidates.filter { sums[it.sum]!!.all { prods[it.prod]!!.size > 1 } }
    val fact2 = fact1.filter { prods[it.prod]!!.intersect(fact1).size == 1 }
    val fact3 = fact2.filter { sums[it.sum]!!.intersect(fact2).size == 1 }
    print("The only solution is : ")
    for ((x, y, _, _) in fact3) println("x = $x, y = $y")
}


/*REXX program sums the first    N    terms of     1/(k**2),          k=1 ──►  N.       */
parse arg N D .                                  /*obtain optional arguments from the CL*/
if N=='' | N==","  then N=1000                   /*Not specified?  Then use the default.*/
if D=='' | D==","  then D=  60                   /* "      "         "   "   "     "    */
numeric digits D                                 /*use D digits (9 is the REXX default).*/
$=0                                              /*initialize the sum to zero.          */
          do k=1  for N                          /* [↓]  compute for   N   terms.       */
          $=$  +  1/k**2                         /*add a squared reciprocal to the sum. */
          end   /*k*/

say 'The sum of'     N     "terms is:"    $      /*stick a fork in it,  we're all done. */


sum = 0
for i =1 to 1000
    sum = sum + 1 /(pow(i,2))
next
decimals(8)
see sum


sum = (array) ->
  array.reduce (x, y) -> x + y

product = (array) ->
  array.reduce (x, y) -> x * y


<cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]>
<cfoutput>#ArraySum(Variables.myArray)#</cfoutput>


(let ((data #(1 2 3 4 5)))     ; the array
  (values (reduce #'+ data)       ; sum
          (reduce #'* data)))     ; product


module main;
  integer i, suma;

  initial begin
  suma = 0;
    for(i = 1; i <= 999; i=i+1)
    begin
        if(i % 3 == 0) suma = suma + i;
        else if(i % 5 == 0) suma = suma + i;
    end
    $display(suma);
    $finish ;
    end
endmodule


fn s35(n int) int {
    mut nn := n-1
    mut threes := nn/3
    mut fives := nn/5
    mut fifteen := nn/15

    threes = 3 * threes * (threes + 1)
    fives = 5 * fives * (fives + 1)
    fifteen = 15 * fifteen * (fifteen + 1)

    nn = (threes + fives - fifteen) / 2

    return nn
}

fn main(){
    println(s35(1000))
}


function print_count(t)
    local cnt = 0
    for k,v in pairs(t) do
        cnt = cnt + 1
    end
    print(cnt .. ' candidates')
end

function make_pair(a,b)
    local t = {}
    table.insert(t, a) -- 1
    table.insert(t, b) -- 2
    return t
end

function setup()
    local candidates = {}
    for x = 2, 98 do
        for y = x + 1, 98 do
            if x + y <= 100 then
                local p = make_pair(x, y)
                table.insert(candidates, p)
            end
        end
    end
    return candidates
end

function remove_by_sum(candidates, sum)
    for k,v in pairs(candidates) do
        local s = v[1] + v[2]
        if s == sum then
            table.remove(candidates, k)
        end
    end
end

function remove_by_prod(candidates, prod)
    for k,v in pairs(candidates) do
        local p = v[1] * v[2]
        if p == prod then
            table.remove(candidates, k)
        end
    end
end

function statement1(candidates)
    local unique = {}
    for k,v in pairs(candidates) do
        local prod = v[1] * v[2]
        if unique[prod] ~= nil then
            unique[prod] = unique[prod] + 1
        else
            unique[prod] = 1
        end
    end

    local done
    repeat
        done = true
        for k,v in pairs(candidates) do
            local prod = v[1] * v[2]
            if unique[prod] == 1 then
                local sum = v[1] + v[2]
                remove_by_sum(candidates, sum)
                done = false
                break
            end
        end
    until done
end

function statement2(candidates)
    local unique = {}
    for k,v in pairs(candidates) do
        local prod = v[1] * v[2]
        if unique[prod] ~= nil then
            unique[prod] = unique[prod] + 1
        else
            unique[prod] = 1
        end
    end

    local done
    repeat
        done = true
        for k,v in pairs(candidates) do
            local prod = v[1] * v[2]
            if unique[prod] > 1 then
                remove_by_prod(candidates, prod)
                done = false
                break
            end
        end
    until done
end

function statement3(candidates)
    local unique = {}
    for k,v in pairs(candidates) do
        local sum = v[1] + v[2]
        if unique[sum] ~= nil then
            unique[sum] = unique[sum] + 1
        else
            unique[sum] = 1
        end
    end

    local done
    repeat
        done = true
        for k,v in pairs(candidates) do
            local sum = v[1] + v[2]
            if unique[sum] > 1 then
                remove_by_sum(candidates, sum)
                done = false
                break
            end
        end
    until done
end

function main()
    local candidates = setup()
    print_count(candidates)

    statement1(candidates)
    print_count(candidates)

    statement2(candidates)
    print_count(candidates)

    statement3(candidates)
    print_count(candidates)

    for k,v in pairs(candidates) do
        local sum = v[1] + v[2]
        local prod = v[1] * v[2]
        print("a=" .. v[1] .. ", b=" .. v[2] .. "; S=" .. sum .. ", P=" .. prod)
    end
end

main()


for i =1 to 1000
  sum = sum + 1 /( i^2)
next i
print sum


def sum_product(a)
    { a.sum(), a.product() }
end


import std.stdio;

void main() {
    immutable array = [1, 2, 3, 4, 5];

    int sum = 0;
    int prod = 1;

    foreach (x; array) {
        sum += x;
        prod *= x;
    }

    writeln("Sum: ", sum);
    writeln("Product: ", prod);
}


1 3 5 7 9 11 13 0ss1sp[dls+sslp*spz0!=a]dsax[Sum: ]Plsp[Product: ]Plpp
Sum: 49
Product: 135135


import sequtils, sets, sugar, tables

var
  xycandidates = toSeq(2..98)
  sums = collect(initHashSet, for s in 5..100: {s})   # Set of possible sums.
  factors: Table[int, seq[(int, int)]]                # Mapping product -> list of factors.

# Build the factor mapping.
for i in 0..<xycandidates.high:
  let x = xycandidates[i]
  for j in (i + 1)..xycandidates.high:
    let y = xycandidates[j]
    factors.mgetOrPut(x * y, @[]).add (x, y)

iterator terms(n: int): (int, int) =
  ## Yield the possible terms (x, y) of a given sum.
  for x in 2..(n - 1) div 2:
    yield (x, n - x)

# S says "P does not know X and Y."
# => For every decomposition of S, there is no product with a single decomposition.
for s in toSeq(sums):
  for (x, y) in s.terms():
    let p = x * y
    if factors[p].len == 1:
      sums.excl s
      break

# P says "Now I know X and Y."
# => P has only one decomposition with sum in "sums".
for p in toSeq(factors.keys):
  var sums = collect(initHashSet):
               for (x, y) in factors[p]:
                 if x + y in sums: {x + y}
  if card(sums) > 1: factors.del p

# S says "Now I also know X and Y."
# => S has only one decomposition with product in "factors".
for s in toSeq(sums):
  var prods = collect(initHashSet):
                for (x, y) in s.terms():
                  if x * y in factors: {x * y}
  if card(prods) > 1: sums.excl s

# Now, combine the sums and the products.
for s in sums:
  for (x, y) in s.terms:
    if x * y in factors: echo (x, y)


all      =.set~new
Call time 'R'
cnt.=0
do a=2 to 100
  do b=a+1 to 100-2
    p=a b
    if a+b>100 then leave b
    all~put(p)
    prd=a*b
    cnt.prd+=1
    End
  End
Say "There are" all~items "pairs where X+Y <=" max "(and X<Y)"

spairs=.set~new
Do Until all~items=0
  do p over all
    d=decompositions(p)
    If take Then
      spairs=spairs~union(d)
    dif=all~difference(d)
    Leave
    End
  all=dif
  end
Say "S starts with" spairs~items "possible pairs."

sProducts.=0
Do p over sPairs
  Parse Var p x y
  prod=x*y
  sProducts.prod+=1
  End

pPairs=.set~new
Do p over sPairs
  Parse Var p xb yb
  prod=xb*yb
  If sProducts.prod=1 Then
    pPairs~put(p)
  End
Say "P then has" pPairs~items "possible pairs."

Sums.=0
Do p over pPairs
  Parse Var p xc yc
  sum=xc+yc
  Sums.sum+=1
  End

final=.set~new
Do p over pPairs
  Parse Var p x y
  sum=x+y
  If Sums.sum=1 Then
    final~put(p)
  End

si=0
Do p Over final
  si+=1
  sol.si=p
  End
Select
  When final~items=1 Then Say "Answer:" sol.1
  When final~items=0 Then Say "No possible answer."
  Otherwise Do;            Say final~items "possible answers:"
                           Do p over final
                             Say p
                             End
    End
  End
Say "Elapsed time:" time('E') "seconds"
Exit

decompositions: Procedure Expose cnt. take spairs
  epairs=.set~new
  Use Arg p
  Parse Var p aa bb
  s=aa+bb
  take=1
  Do xa=2 To s/2
    ya=s-xa
    pp=xa ya
    epairs~put(pp)
    prod=xa*ya
    If cnt.prod=1 Then
      take=0
    End
  return epairs


const LOWER: i32 = 1;
const UPPER: i32 = 1000;

// Because the rule for our series is simply adding one, the number of terms are the number of
// digits between LOWER and UPPER
const NUMBER_OF_TERMS: i32 = (UPPER + 1) - LOWER;
fn main() {
    // Formulaic method
    println!("{}", (NUMBER_OF_TERMS * (LOWER + UPPER)) / 2);
    // Naive method
    println!("{}", (LOWER..UPPER + 1).fold(0, |sum, x| sum + x));
}


data _null_;
s=0;
do n=1 to 1000;
   s+1/n**2;        /* s+x is synonym of s=s+x */
end;
e=s-constant('pi')**2/6;
put s e;
run;


program SumAndProductOfArray;

{$APPTYPE CONSOLE}

var
  i: integer;
  lIntArray: array [1 .. 5] of integer = (1, 2, 3, 4, 5);
  lSum: integer = 0;
  lProduct: integer = 1;
begin
  for i := 1 to length(lIntArray) do
  begin
    Inc(lSum, lIntArray[i]);
    lProduct := lProduct * lIntArray[i]
  end;

  Write('Sum: ');
  Writeln(lSum);
  Write('Product: ');
  Writeln(lProduct);
end.


include c:\cxpl\stdlib;

func Sum1;      \Return sum the straightforward way
int  N, S;
[S:= 0;
for N:= 1 to 999 do
    if rem(N/3)=0 or rem(N/5)=0 then S:= S+N;
return S;
];

func Sum2(D);   \Return sum of sequence using N*(N+1)/2
int  D;
int  Q;
[Q:= (1000-1)/D;
return Q*(Q+1)/2*D;
];

func Sum3(D);   \Return sum of sequence for really big number
string 0;       \don't terminate strings by setting most significant bit
int  D;         \divisor
int  I;
char P(40), Q(40), R(40);       \product, quotient, result
[StrNDiv("99999999999999999999", D, Q, 20);     \Q:= (1E20-1)/D
for I:= 0 to 17 do R(I):= ^0;                   \R:= D
R(18):= D/10 +^0;
R(19):= rem(0) +^0;
StrNMul(Q, R, P, 20);                           \P:= Q*R = Q*D
StrNAdd("00000000000000000001", Q, 20);         \Q:= Q+1
StrNMul(P+20, Q, R, 20);                        \R:= P*Q = Q*D*(Q+1)
StrNDiv(R, 2, Q, 40);                           \Q:= P/2 = Q*D*(Q+1)/2
return Q;                                       \(very temporary location)
];

char S(40), T;
[IntOut(0, Sum1);  CrLf(0);
 IntOut(0, Sum2(3) + Sum2(5) - Sum2(3*5));  CrLf(0);
StrNCopy(Sum3(3), S, 40);
StrNAdd(Sum3(5), S, 40);
T:= Sum3(3*5);
StrNSub(S, T, 40);
TextN(0, T, 40);  CrLf(0);
]


const std = @import("std");
const stdout = std.io.getStdOut().writer();

fn sumdiv(n: i64, d: i64) i128 {
    var m: i128 = @divFloor(n, d);
    return @divExact(m * (m + 1), 2) * d;
}

fn sum3or5(n: i64) i128 {
    return sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15);
}

pub fn main() !void {
    try stdout.print("The sum of the multiples of 3 and 5 below 1000 is {}\n", .{sum3or5(999)});
    try stdout.print("The sum of the multiples of 3 and 5 below 1e18 is {}\n", .{sum3or5(999_999_999_999_999_999)});
}


use List::Util qw(none);

sub grep_unique {
    my($by, @list) = @_;
    my @seen;
    for (@list) {
        my $x = &$by(@$_);
        $seen[$x]= defined $seen[$x] ? 0 : join ' ', @$_;
    }
    grep { $_ } @seen;
}

sub sums {
    my($n) = @_;
    my @sums;
    push @sums, [$_, $n - $_] for 2 .. int $n/2;
    @sums;
}

sub sum     { $_[0] + $_[1] }
sub product { $_[0] * $_[1] }

for $i (2..97) {
    push @all_pairs, map { [$i, $_] } $i + 1..98
}

# Fact 1:
%p_unique = map { $_ => 1 } grep_unique(\&product, @all_pairs);
for my $p (@all_pairs) {
    push @s_pairs, [@$p] if none { $p_unique{join ' ', @$_} } sums sum @$p;
}

# Fact 2:
@p_pairs = map { [split ' ', $_] } grep_unique(\&product, @s_pairs);

# Fact 3:
@final_pair = grep_unique(\&sum, @p_pairs);

printf "X = %d, Y = %d\n", split ' ', $final_pair[0];


with javascript_semantics
function satisfies_statement1(integer s)
-- S says: P does not know the two numbers.
-- Given s, for /all/ pairs (a,b), a+b=s, 2<=a,b<=99, at least one of a or b is composite
    for a=2 to floor(s/2) do
        if is_prime(a) and is_prime(s-a) then
            return false
        end if
    end for
    return true
end function

function satisfies_statement2(integer p)
-- P says: Now I know the two numbers.
-- Given p, for /all/ pairs (a,b), a*b=p, 2<=a,b<=99, exactly one pair satisfies statement 1
    bool winner = false
    for i=2 to floor(sqrt(p)) do
        if mod(p,i)=0 then
            integer j = floor(p/i)
            if 2<=j and j<=99 then
                if satisfies_statement1(i+j) then
                    if winner then return false end if
                    winner = true
                end if
            end if
        end if
    end for
    return winner
end function

function satisfies_statement3(integer s)
-- S says: Now I know the two numbers.
-- Given s, for /all/ pairs (a,b), a+b=s, 2<=a,b<=99, exactly one pair satisfies statements 1 and 2
    integer winner = 0
    if satisfies_statement1(s) then
        for a=2 to floor(s/2) do
            if satisfies_statement2(a*(s-a)) then
                if winner then return 0 end if
                winner = a
            end if
        end for
    end if
    return winner
end function

for s=2 to 100 do
    integer a = satisfies_statement3(s)
    if a!=0 then
        printf(1,"%d (%d+%d)\n",{s,a,s-a})
    end if
end for


(define (sum a b fn)
  (do ((i a (+ i 1))
       (result 0 (+ result (fn i))))
      ((> i b) result)))

(sum 1 1000 (lambda (x) (/ 1 (* x x)))) ; fraction
(exact->inexact (sum 1 1000 (lambda (x) (/ 1 (* x x))))) ; decimal


$ include "seed7_05.s7i";
  include "float.s7i";

const func float: invsqr (in float: n) is
  return 1.0 / n**2;

const proc: main is func
  local
    var integer: i is 0;
    var float: sum is 0.0;
  begin
    for i range 1 to 1000 do
      sum +:= invsqr(flt(i));
    end for;
    writeln(sum digits 6 lpad 8);
  end func;


pragma.enable("accumulator")
accum 0 for x in [1,2,3,4,5] { _ + x }
accum 1 for x in [1,2,3,4,5] { _ * x }


class
	APPLICATION

create
	make

feature {NONE}

	make
		local
			test: ARRAY [INTEGER]
		do
			create test.make_empty
			test := <<5, 1, 9, 7>>
			io.put_string ("Sum: " + sum (test).out)
			io.new_line
			io.put_string ("Product: " + product (test).out)
		end

	sum (ar: ARRAY [INTEGER]): INTEGER
			-- Sum of the items of the array 'ar'.
		do
			across
				ar.lower |..| ar.upper as c
			loop
				Result := Result + ar [c.item]
			end
		end

	product (ar: ARRAY [INTEGER]): INTEGER
			-- Product of the items of the array 'ar'.
		do
			Result := 1
			across
				ar.lower |..| ar.upper as c
			loop
				Result := Result * ar [c.item]
			end
		end

end


main =>
    N = 98,
    PD = new_array(N*N), % PD[I] = no. of product decompositions of I
    foreach(I in 1..N*N) PD[I] = 0 end,
    foreach(X in 2..N-1, Y in X+1..N) PD[X * Y] := PD[X * Y] + 1 end,

    % Fact 1: S says "P does not know X and Y.", i.e.
    % For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition:
    Solutions1 = [[X,Y] : X in 2..N-1, Y in X+1..100-X, foreach(XX in 2..X+Y-3) PD[XX * (X+Y-XX)] > 1 end],

    % Fact 2: P says "Now I know X and Y.", i.e.
    % The number X*Y has only one product decomposition for which fact 1 is true:
    Solutions2 = [[X,Y] : [X,Y] in Solutions1, foreach([XX,YY] in Solutions1, XX * YY = X * Y) XX = X, YY = Y end],

    % Fact 3: S says "Now I also know X and Y.", i.e.
    % The number X+Y has only one sum decomposition for which fact 2 is true.
    Solutions3 = [[X,Y] : [X,Y] in Solutions2, foreach([XX,YY] in Solutions2, XX + YY = X + Y) XX = X, YY = Y end],

    println(Solutions3).


#!/usr/bin/env python

from collections import Counter

def decompose_sum(s):
    return [(a,s-a) for a in range(2,int(s/2+1))]

# Generate all possible pairs
all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)

# Fact 1 --> Select pairs for which all sum decompositions have non-unique product
product_counts = Counter(c*d for c,d in all_pairs)
unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)
s_pairs = [(a,b) for a,b in all_pairs if
    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]

# Fact 2 --> Select pairs for which the product is unique
product_counts = Counter(c*d for c,d in s_pairs)
p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]

# Fact 3 --> Select pairs for which the sum is unique
sum_counts = Counter(c+d for c,d in p_pairs)
final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]

print(final_pairs)


#lang racket
(define-syntax-rule (define/mem (name args ...) body ...)
  (begin
    (define cache (make-hash))
    (define (name args ...)
      (hash-ref! cache (list args ...) (lambda () body ...)))))

(define (sum p) (+ (first p) (second p)))
(define (mul p) (* (first p) (second p)))

(define (sum= p s) (filter (lambda (q) (= p (sum q))) s))
(define (mul= p s) (filter (lambda (q) (= p (mul q))) s))

(define (puzzle tot)
  (printf "Max Sum: ~a\n" tot)
  (define s1 (for*/list ([x (in-range 2 (add1 tot))]
                         [y (in-range (add1 x) (- (add1 tot) x))])
               (list x y)))
  (printf "Possible pairs: ~a\n" (length s1))

  (define/mem (sumEq/all p) (sum= p s1))
  (define/mem (mulEq/all p) (mul= p s1))

  (define s2 (filter (lambda (p) (andmap (lambda (q)
                                           (not (= (length (mulEq/all (mul q))) 1)))
                                         (sumEq/all (sum p))))
                     s1))
  (printf "Initial pairs for S: ~a\n" (length s2))

  (define s3 (filter (lambda (p) (= (length (mul= (mul p) s2)) 1))
                   s2))
  (displayln (length s3))
  (printf "Pairs for P: ~a\n" (length s3))

  (define s4 (filter (lambda (p) (= (length (sum= (sum p) s3)) 1))
                     s3))
  (printf "Final pairs for S: ~a\n" (length s4))

  (displayln s4))

(puzzle 100)


((1 to: 1000) reduce: [|:x :y | x + (y squared reciprocal as: Float)]).


( (1 to: 1000) fold: [:sum :aNumber |
  sum + (aNumber squared reciprocal) ] ) asFloat displayNl.


CREATE TABLE t1 (n REAL);
-- this is postgresql specific, fill the table
INSERT INTO t1 (SELECT generate_series(1,1000)::REAL);
WITH tt AS (
  SELECT 1/(n*n) AS recip FROM t1
) SELECT SUM(recip) FROM tt;


import system'routines;
import extensions;

public program()
{
    var list := new int[]{1, 2, 3, 4, 5 };

    var sum := list.summarize(new Integer());
    var product := list.accumulate(new Integer(1), (var,val => var * val));
}


iex(26)> Enum.reduce([1,2,3,4,5], 0, fn x,acc -> x+acc end)
15
iex(27)> Enum.reduce([1,2,3,4,5], 1, fn x,acc -> x*acc end)
120
iex(28)> Enum.reduce([1,2,3,4,5], fn x,acc -> x+acc end)
15
iex(29)> Enum.reduce([1,2,3,4,5], fn x,acc -> x*acc end)
120
iex(30)> Enum.reduce([], 0, fn x,acc -> x+acc end)
0
iex(31)> Enum.reduce([], 1, fn x,acc -> x*acc end)
1
iex(32)> Enum.reduce([], fn x,acc -> x+acc end)
** (Enum.EmptyError) empty error
    (elixir) lib/enum.ex:1287: Enum.reduce/2
iex(32)> Enum.reduce([], fn x,acc -> x*acc end)
** (Enum.EmptyError) empty error
    (elixir) lib/enum.ex:1287: Enum.reduce/2


(let ((array [1 2 3 4 5]))
  (apply #'+ (append array nil))
  (apply #'* (append array nil)))


% create the list:
L = lists:seq(1, 10).

% and compute its sum:
S = lists:sum(L).
P = lists:foldl(fun (X, P) -> X * P end, 1, L).


sub grep-unique (&by, @list) { @list.classify(&by).values.grep(* == 1).map(*[0]) }
sub sums        ($n)         { ($_, $n - $_ for 2 .. $n div 2) }
sub sum         ([$x, $y])   { $x + $y }
sub product     ([$x, $y])   { $x * $y }

my @all-pairs = (|($_ X $_+1 .. 98) for 2..97);

# Fact 1:
my %p-unique := Set.new: map ~*, grep-unique &product, @all-pairs;
my @s-pairs = @all-pairs.grep: { none (%p-unique{~$_} for sums sum $_) };

# Fact 2:
my @p-pairs = grep-unique &product, @s-pairs;

# Fact 3:
my @final-pairs = grep-unique &sum, @p-pairs;

printf "X = %d, Y = %d\n", |$_ for @final-pairs;


debug=0
If debug Then Do
  oid='sppn.txt'; 'erase' oid
  End
Call time 'R'
all_pairs=''
cnt.=0
i=0
/* first take all possible pairs 2<=x<y with x+y<=100 */
/* and compute the respective sums and products       */
/* count the number of times a sum or product occurs  */
Do x=2 To 98
  Do y=x+1 To 100-x
    x=right(x,2,0)
    y=right(y,2,0)
    all_pairs=all_pairs x'/'y
    i=i+1
    x.i=x
    y.i=y
    sum=x+y
    prd=x*y
    cnt.0s.sum=cnt.0s.sum+1
    cnt.0p.prd=cnt.0p.prd+1
    End
  End
n=i
/* now compute the possible pairs for each sum sum_d.sum */
/*                                 and product prd_d.prd */
/* also the list of possible sums and products suml, prdl*/
sum_d.=''
prd_d.=''
suml=''
prdl=''
Do i=1 To n
  x=x.i
  y=y.i
  x=right(x,2,0)
  y=right(y,2,0)
  sum=x+y
  prd=x*y
  cnt.0s.x.y=cnt.0s.sum
  cnt.0p.x.y=cnt.0p.prd
  sum_d.sum=sum_d.sum x'/'y
  prd_d.prd=prd_d.prd x'/'y
  If wordpos(sum,suml)=0 Then suml=suml sum
  If wordpos(prd,prdl)=0 Then prdl=prdl prd
  End
Say n 'possible pairs'
Call o 'SUM'
suml=wordsort(suml)
prdl=wordsort(prdl)
sumlc=suml
si=0
pi=0
Do While sumlc>''
  Parse Var sumlc sum sumlc
  si=si+1
  sum.si=sum
  si.sum=si
  If sum=17 Then sx=si
  temp=prdl
  Do While temp>''
    Parse Var temp prd temp
    If si=1 Then Do
      pi=pi+1
      prd.pi=prd
      pi.prd=pi
      If prd=52 Then px=pi
      End
    A.prd.sum='+'
    End
  End
sin=si
pin=pi
Call o 'SUM'
Do si=1 To sin
  Call o f5(si) f3(sum.si)
  End
Call o 'PRD'
Do pi=1 To pin
  Call o f5(pi) f6(prd.pi)
  End
a.='-'
Do pi=1 To pin
  prd=prd.pi
  Do si=1 To sin
    sum=sum.si
    Do sj=1 To words(sum_d.sum)
      If wordpos(word(sum_d.sum,sj),prd_d.prd)>0 Then
        Parse Value word(sum_d.sum,sj) with x '/' y
        prde=x*y
        sume=x+y
        pa=pi.prde
        sa=si.sume
        a.pa.sa='+'
      End
    End
  End
Call show '1'

Do pi=1 To pin
  prow=''
  cnt=0
  Do si=1 To sin
    If a.pi.si='+' Then Do
      cnt=cnt+1
      pj=pi
      sj=si
      End
    End
  If cnt=1 Then
    a.pj.sj='1'
  End
Call show '2'

Do si=1 To sin
  Do pi=1 To pin
    If a.pi.si='1' Then Leave
    End
  If pi<=pin Then Do
    Do pi=1 To pin
      If a.pi.si='+' Then
        a.pi.si='2'
      End
    End
  End
Call show '3'

Do pi=1 To pin
  prow=''
  Do si=1 To sin
    prow=prow||a.pi.si
    End
  If count('+',prow)>1 Then Do
    Do si=1 To sin
      If a.pi.si='+' Then
        a.pi.si='3'
      End
    End
  End
Call show '4'

Do si=1 To sin
  scol=''
  Do pi=1 To pin
    scol=scol||a.pi.si
    End
  If count('+',scol)>1 Then Do
    Do pi=1 To pin
      If a.pi.si='+' Then
        a.pi.si='4'
      End
    End
  End
Call show '5'

sol=0
Do pi=1 To pin
  Do si=1 To sin
    If a.pi.si='+' Then Do
      Say sum.si prd.pi
      sum=sum.si
      prd=prd.pi
      sol=sol+1
      End
    End
  End
Say sol 'solution(s)'
Say '            possible pairs'
Say 'Product='prd prd_d.52
Say '    Sum='sum sum_d.17
Say 'The only pair in both lists is 04/13.'
Say 'Elapsed time:' time('E') 'seconds'
Exit
show:
If debug Then Do
  Call o 'show' arg(1)
  Do pi=1 To 60
    ol=''
    Do si=1 To 60
      ol=ol||a.pi.si
      End
    Call o ol
    End
  Say 'a.'px'.'sx'='a.px.sx
  End
Return

Exit
o: Return lineout(oid,arg(1))
f3: Return format(arg(1),3)
f4: Return format(arg(1),4)
f5: Return format(arg(1),5)
f6: Return format(arg(1),6)

count: Procedure
  Parse Arg c,s
  s=translate(s,c,c||xrange('00'x,'ff'x))
  s=space(s,0)
  Return length(s)
wordsort: Procedure
/**********************************************************************
* Sort the list of words supplied as argument. Return the sorted list
**********************************************************************/
  Parse Arg wl
  wa.=''
  wa.0=0
  Do While wl<>''
    Parse Var wl w wl
    Do i=1 To wa.0
      If wa.i>w Then Leave
      End
    If i<=wa.0 Then Do
      Do j=wa.0 To i By -1
        ii=j+1
        wa.ii=wa.j
        End
      End
    wa.i=w
    wa.0=wa.0+1
    End
  swl=''
  Do i=1 To wa.0
    swl=swl wa.i
    End
  /* Say swl */
  Return strip(swl)


func sumSeries(var n: Int) -> Double {
    var ret: Double = 0

    for i in 1...n {
        ret += (1 / pow(Double(i), 2))
    }

    return ret
}

output: 1.64393456668156


package require Tcl 8.5
namespace path {::tcl::mathop ::tcl::} ;# Ease of access to mathop commands
proc lsum_series {l} {+ {*}[lmap n $l {/ [** $n 2]}]} ;# an expr would be clearer, but this is a demonstration of mathop

# using range function defined below
lsum_series [range 1 1001] ;# ==> 1.6439345666815615


sequence array
integer sum,prod

array = { 1, 2, 3, 4, 5 }

sum = 0
prod = 1
for i = 1 to length(array) do
  sum += array[i]
  prod *= array[i]
end for

printf(1,"sum is %d\n",sum)
printf(1,"prod is %d\n",prod)


let numbers = [| 1..10 |]
let sum = numbers |> Array.sum
let product = numbers |> Array.reduce (*)


def add(x,y) x + y end
def mul(x,y) x * y end

def sumEq(s,p) s.select{|q| add(*p) == add(*q)} end
def mulEq(s,p) s.select{|q| mul(*p) == mul(*q)} end

s1 = (a = *2...100).product(a).select{|x,y| x<y && x+y<100}
s2 = s1.select{|p| sumEq(s1,p).all?{|q| mulEq(s1,q).size != 1} }
s3 = s2.select{|p| (mulEq(s1,p) & s2).size == 1}
p    s3.select{|p| (sumEq(s1,p) & s3).size == 1}


object ImpossiblePuzzle extends App {
  type XY = (Int, Int)
  val step0 = for {
    x <- 1 to 100
    y <- 1 to 100
    if 1 < x && x < y && x + y < 100
  } yield (x, y)

  def sum(xy: XY) = xy._1 + xy._2
  def prod(xy: XY) = xy._1 * xy._2
  def sumEq(xy: XY) = step0 filter { sum(_) == sum(xy) }
  def prodEq(xy: XY) = step0 filter { prod(_) == prod(xy) }

  val step2 = step0 filter { sumEq(_) forall { prodEq(_).size != 1 }}
  val step3 = step2 filter { prodEq(_).intersect(step2).size == 1 }
  val step4 = step3 filter { sumEq(_).intersect(step3).size == 1 }
  println(step4)
}


term() {
   b=$1;res=$2
   echo "scale=5;1/($res*$res)+$b" | bc
}

sum() {
  (read B; res=$1;
  test -n "$B" && (term $B $res) || (term 0 $res))
}

fold() {
  func=$1
  (while read a ; do
      fold $func | $func $a
  done)
}

(echo 3; echo 1; echo 4) | fold sum


1 2 3 4 5 {input "array"}
5         {length of input}
0s:       {sum}
1p:       {product}

[$0=~][1-\$s;+s:p;*p:]#%

"Sum: "s;."
Product: "p;.


class Main
{
  public static Void main ()
  {
    Int[] array := (1..20).toList

    // you can use a loop
    Int sum := 0
    array.each |Int n| { sum += n }
    echo ("Sum of array is : $sum")

    Int product := 1
    array.each |Int n| { product *= n }
    echo ("Product of array is : $product")

    // or use 'reduce'
    // 'reduce' takes a function,
    //       the first argument is the accumulated value
    //       and the second is the next item in the list
    sum = array.reduce(0) |Obj r, Int v -> Obj|
    {
      return (Int)r + v
    }
    echo ("Sum of array : $sum")

    product = array.reduce(1) |Obj r, Int v -> Obj|
    {
      return (Int)r * v
    }
    echo ("Product of array : $product")
  }
}


: third ( a b c -- a b c a ) 2 pick ;
: reduce ( xt n addr cnt -- n' ) \ where xt ( a b -- n )
  cells bounds do i @ third execute  cell +loop nip ;

create a 1 , 2 , 3 , 4 , 5 ,

' + 0 a 5 reduce .    \ 15
' * 1 a 5 reduce .    \ 120


(import (scheme base)
        (scheme cxr)
        (scheme write)
        (srfi 1))

;; utility method to find unique sum/product in given list
(define (unique-items lst key)
  (let ((all-items (map key lst)))
    (filter (lambda (i) (= 1 (count (lambda (p) (= p (key i)))
                                    all-items)))
            lst)))

;; list of all (x y x+y x*y) combinations with y > x
(define *xy-pairs*
  (apply append
         (map (lambda (i)
                (map (lambda (j)
                       (list i j (+ i j) (* i j)))
                     (iota (- 98 i) (+ 1 i))))
              (iota 96 2))))

;; S says "P does not know X and Y"
(define *products* ; get products which have multiple decompositions
  (let ((all-products (map fourth *xy-pairs*)))
    (filter (lambda (p) (> (count (lambda (i) (= i p)) all-products) 1))
            all-products)))

(define *fact-1* ; every x+y has x*y in *products*
  (filter (lambda (i)
            (every (lambda (p) (memq (fourth p) *products*))
                   (filter (lambda (p) (= (third i) (third p))) *xy-pairs*)))
          *xy-pairs*))

;; P says "Now I know X and Y"
(define *fact-2* ; find the unique X*Y
  (unique-items *fact-1* fourth))

;; S says "Now I also know X and Y"
(define *fact-3* ; find the unique X+Y
  (unique-items *fact-2* third))

(display (string-append "Initial pairs: " (number->string (length *xy-pairs*)) "\n"))
(display (string-append "After S: " (number->string (length *fact-1*)) "\n"))
(display (string-append "After P: " (number->string (length *fact-2*)) "\n"))
(display (string-append "After S: " (number->string (length *fact-3*)) "\n"))
(display (string-append "X: "
                        (number->string (caar *fact-3*))
                        " Y: "
                        (number->string (cadar *fact-3*))
                        "\n"))


#import flo
#import nat

#cast %e

total = plus:-0 div/*1. sqr* float*t iota 1001


public static void main(){
	int i, start = 1, end = 1000;
	double sum = 0.0;

	for(i = start; i<= end; i++)
		sum += (1 / (double)(i * i));

	stdout.printf("%s\n", sum.to_string());
}


integer, dimension(10) :: a = (/ (i, i=1, 10) /)
integer :: sresult, presult

sresult = sum(a)
presult = product(a)


' FB 1.05.0 Win64

Dim a(1 To 4) As Integer = {1, 4, 6, 3}
Dim As Integer i, sum = 0, prod = 1
For i = 1 To 4
  sum  += a(i)
  prod *= a(i)
Next
Print "Sum     ="; sum
Print "Product ="; prod
Print
Print "Press any key to quit"
Sleep


func grep_uniq(a, by) { a.group_by{ .(by) }.values.grep{.len == 1}.map{_[0]} }
func sums     (n)     { 2 .. n//2 -> map {|i| [i, n-i] } }

var pairs = (2..97 -> map {|i| ([i] ~X (i+1 .. 98))... })

var p_uniq = Hash()
p_uniq{grep_uniq(pairs, :prod).map { .to_s }...} = ()

var s_pairs = pairs.grep {|p| sums(p.sum).all { !p_uniq.contains(.to_s) } }
var p_pairs = grep_uniq(s_pairs, :prod)
var f_pairs = grep_uniq(p_pairs, :sum)

f_pairs.each { |p| printf("X = %d, Y = %d\n", p...) }


import "/dynamic" for Tuple
import "/seq" for Lst

var P = Tuple.create("P", ["x", "y", "sum", "prod"])

var intersect = Fn.new { |l1, l2|
    var l3 = (l1.count < l2.count) ? l1 : l2
    var l4 = (l3 == l1) ? l2 : l1
    var l5 = []
    for (e in l3) if (l4.contains(e)) l5.add(e)
    return l5
}

var candidates = []
for (x in 2..49) {
    for (y in x + 1..100 - x) {
        candidates.add(P.new(x, y, x + y, x * y))
    }
}

var sumGroups  = Lst.groups(candidates) { |c| c.sum }
var prodGroups = Lst.groups(candidates) { |c| c.prod }
var sumMap = {}
for (sumGroup in sumGroups) {
    sumMap[sumGroup[0]] = sumGroup[1].map { |l| l[0] }.toList
}
var prodMap = {}
for (prodGroup in prodGroups) {
    prodMap[prodGroup[0]] = prodGroup[1].map { |l| l[0] }.toList
}
var fact1 = candidates.where { |c| sumMap[c.sum].all { |c| prodMap[c.prod].count > 1 } }.toList
var fact2 = fact1.where { |c| intersect.call(prodMap[c.prod], fact1).count == 1 }.toList
var fact3 = fact2.where { |c| intersect.call(sumMap[c.sum], fact2).count == 1 }.toList
System.write("The only solution is : ")
for (p in fact3) System.print("x = %(p.x), y = %(p.y)")


Private Function sumto(n As Integer) As Double
    Dim res As Double
    For i = 1 To n
        res = res + 1 / i ^ 2
    Next i
    sumto = res
End Function
Public Sub main()
    Debug.Print sumto(1000)
End Sub


' Sum of a series
    for i=1 to 1000
        s=s+1/i^2
    next
    wscript.echo s


' Sum of a series
    Sub SumOfaSeries()
        Dim s As Double
        s = 0
        For i = 1 To 1000
            s = s + 1 / i ^ 2
        Next 'i
        Console.WriteLine(s)
    End Sub


Public Sub Main()
Dim iList As Integer[] = [1, 2, 3, 4, 5]
Dim iSum, iCount As Integer
Dim iPrd As Integer = 1

For iCount = 0 To iList.Max
  iSum += iList[iCount]
  iPrd *= iList[iCount]
Next

Print "The Sum =\t" & iSum
Print "The Product =\t" & iPrd

End


mul:=Utils.Helpers.summer.fp1('*,1); //-->list.reduce('*,1), multiply list items
var allPairs=[[(a,b); [2..100]; { [a+1..100] },{ a+b<100 }; ROList]]; // 2,304 pairs

sxys,pxys:=Dictionary(),Dictionary();  // hashes of allPairs sums and products: 95,1155
foreach xy in (allPairs){ sxys.appendV(xy.sum(),xy); pxys.appendV(xy:mul(_),xy) }

sOK:= 'wrap(s){ (not sxys[s].filter1('wrap(xy){ pxys[xy:mul(_)].len()<2 })) };
pOK:= 'wrap(p){ 1==pxys[p].filter('wrap([(x,y)]){ sOK(x+y) }).len() };
sOK2:='wrap(s){ 1==sxys[s].filter('wrap(xy){ pOK(xy:mul(_)) }).len() };
allPairs.filter('wrap([(x,y)]){ sOK(x+y) and pOK(x*y) and sOK2(x+y) })
.println();


import math

fn main(){
    println('known:    ${math.pi*math.pi/6}')
    mut sum := f64(0)
    for i :=1e3; i >0; i-- {
        sum += 1/(i*i)
    }
    println('computed: $sum')
}


let s => import 'stream';

s.range 1 1001
-> s.map (@ inner k => / 1 (* k k))
-> s.reduce 0 +
-- io.writeln io.stdout
;


var sumSeries = Fn.new { |n| (1..n).reduce(0) { |sum, i| sum + 1/(i*i) } }

System.print("s(1000) = %(sumSeries.call(1000))")
System.print("zeta(2) = %(Num.pi*Num.pi/6)")


v := [1 .. 8];

Sum(v);
# 36

Product(v);
# 40320

# You can sum or multiply the result of a function

Sum(v, n -> n^2);
# 204

Product(v, n -> 1/n);
# 1/40320


DIM a%(10)
' put some values into the array
FOR i%=1 TO 10
  a%(i%)=i%
NEXT i%
'
sum%=0
product%=1
FOR i%=1 TO 10
  sum%=sum%+a%(i%)
  product%=product%*a%(i%)
NEXT i%
'
PRINT "Sum is ";sum%
PRINT "Product is ";product%


package main

import "fmt"

func main() {
    sum, prod := 0, 1
    for _, x := range []int{1,2,5} {
        sum += x
        prod *= x
    }
    fmt.Println(sum, prod)
}


code CrLf=9;  code real RlOut=48;
int  X;  real S;
[S:= 0.0;
for X:= 1 to 1000 do S:= S + 1.0/float(X*X);
RlOut(0, S);  CrLf(0);
]


const std = @import("std");

fn f(x: i64) f64 {
    return 1/@intToFloat(f64, x*x);
}

fn S(fun: fn(i64) f64, n: i64) f64 {
    var s: f64 = 0.0;
    var i: i64 = n;

    while (i > 0) : (i -= 1) {
        s += fun(i);
    }
    return s;
}

pub fn main() !void
{
    const stdout = std.io.getStdOut().writer();
    try stdout.print("S_1000 = {d:.15}\n", .{S(f, 1000)});
}


10 REM Create an array with some test DATA in it
20 DIM A(5)
30 FOR I = 1 TO 5: READ A(I): NEXT I
40 DATA 1, 2, 3, 4, 5
50 REM Find the sum of elements in the array
60 S = 0
65 P = 1
70 FOR I = 1 TO 5
72 S = SUM + A(I)
75 P = P * A(I)
77 NEXT I
80 PRINT "The sum is "; S;
90 PRINT " and the product is "; P


values = [1..10]

s = sum values           -- the easy way
p = product values

s1 = foldl (+) 0 values  -- the hard way
p1 = foldl (*) 1 values


10 LET n=1000
20 LET s=0
30 FOR k=1 TO n
40 LET s=s+1/(k*k)
50 NEXT k
60 PRINT s


array = $ ! 1, 2, ..., LEN(array)

sum = SUM(array)

product = 1 ! no built-in product function in HicEst
DO i = 1, LEN(array)
  product = product * array(i)
ENDDO

WRITE(ClipBoard, Name) n, sum, product ! n=100; sum=5050; product=9.33262154E157;


procedure main(arglist)
every ( sum := 0 ) +:= !arglist
every ( prod := 1 ) *:= !arglist
write("sum := ", sum,", prod := ",prod)
end


array = [3,6,8]
print,total(array)
print,product(array)


Sum And Product is a room.

To decide which number is the sum of (N - number) and (M - number) (this is summing):
	decide on N + M.

To decide which number is the product of (N - number) and (M - number) (this is production):
	decide on N * M.

When play begins:
	let L be {1, 2, 3, 4, 5};
	say "List: [L in brace notation], sum = [summing reduction of L], product = [production reduction of L].";
	end the story.


public class SumProd
{
 public static void main(final String[] args)
 {
  int sum = 0;
  int prod = 1;
  int[] arg = {1,2,3,4,5};
  for (int i : arg)
  {
   sum += i;
   prod *= i;
  }
 }
}


var array = [1, 2, 3, 4, 5],
    sum = 0,
    prod = 1,
    i;
for (i = 0; i < array.length; i += 1) {
    sum += array[i];
    prod *= array[i];
}
alert(sum + ' ' + prod);


// version 1.1.2

fun main(args: Array<String>) {
    val a = intArrayOf(1, 5, 8, 11, 15)
    println("Array contains : ${a.contentToString()}")
    val sum = a.sum()
    println("Sum is $sum")
    val product = a.fold(1) { acc, i -> acc * i }
    println("Product is $product")
}


val .arr = series 19
writeln "  array: ", .arr
writeln "    sum: ", fold f .x + .y, .arr
writeln "product: ", fold f .x x .y, .arr


local(x = array(1,2,3,4,5,6,7,8,9,10))
// sum of array elements
'Sum: '
with n in #x
sum #n
'\r'
// product of arrray elements
'Product: '
local(product = 1)
with n in #x do => { #product *= #n }
#product


Dim array(19)

For i = 0 To 19
    array(i) = Int(Rnd(1) * 20)
Next i

'product must first equal one or you will get 0 as the product
product = 1
For i = 0 To 19
    sum = (sum + array(i))
    product = (product * array(i))
next i

Print "Sum is " + str$(sum)
Print "Product is " + str$(product)


on sum (intList)
  res = 0
  repeat with v in intList
    res = res + v
  end repeat
  return res
end

on product (intList)
  res = 1
  repeat with v in intList
    res = res * v
  end repeat
  return res
end


//sum
put "1,2,3,4" into nums
split nums using comma
answer sum(nums)

// product
local prodNums
repeat for each element n in nums
    if prodNums is empty then
        put n into prodNums
    else
        multiply prodnums by n
    end if
end repeat
answer prodnums


print apply "sum arraytolist {1 2 3 4 5}
print apply "product arraytolist {1 2 3 4 5}


function sumf(a, ...) return a and a + sumf(...) or 0 end
function sumt(t) return sumf(unpack(t)) end
function prodf(a, ...) return a and a * prodf(...) or 1 end
function prodt(t) return prodf(unpack(t)) end

print(sumt{1, 2, 3, 4, 5})
print(prodt{1, 2, 3, 4, 5})


[%sum,product%]
 where
    x = 1 fby x + 1;
    sum = 0 fby sum + x;
    product = 1 fby product * x
 end


Module Checkit {
      a = (1,2,3,4,5,6,7,8,9,10)
      print a#sum() = 55
      sum = lambda->{push number+number}
      product = lambda->{Push number*number}
      print a#fold(lambda->{Push number*number}, 1), a#fold(lambda->{push number+number},0)
      dim a(2,2) = 5
      Print a()#sum() = 20
}
checkit


a = {1, 2, 3, 4, 5}
Plus @@ a
Apply[Plus, a]
Total[a]
[email protected]
a // Total
Sum[a[[i]], {i, 1, Length[a]}]
Sum[i, {i, a}]


arr = #(1, 2, 3, 4, 5)
sum = 0
for i in arr do sum += i
product = 1
for i in arr do product *= i


(1 2 3 4 5) ((sum) (1 '* reduce)) cleave
"Sum: $1\nProduct: $2" get-stack % puts


^	1	ПE	+	П0	КИП0	x#0	18	^	ИПD
+	ПD	<->	ИПE	*	ПE	БП	05	С/П


MODULE Sumprod EXPORTS Main;

FROM IO IMPORT Put;
FROM Fmt IMPORT Int;

VAR a := ARRAY [1..5] OF INTEGER {1, 2, 3, 4, 5};
VAR sum: INTEGER := 0;
VAR prod: INTEGER := 1;

BEGIN
  FOR i := FIRST(a) TO LAST(a) DO
    INC(sum, a[i]);
    prod := prod * a[i];
  END;
  Put("Sum of array: " & Int(sum) & "\n");
  Put("Product of array: " & Int(prod) & "\n");
END Sumprod.


SUMPROD(A)
 ;Compute the sum and product of the numbers in the array A
 NEW SUM,PROD,POS
 ;SUM is the running sum,
 ;PROD is the running product,
 ;POS is the position within the array A
 SET SUM=0,PROD=1,POS=""
 FOR  SET POS=$ORDER(A(POS)) Q:POS=""  SET SUM=SUM+A(POS),PROD=PROD*A(POS)
 WRITE !,"The sum of the array is "_SUM
 WRITE !,"The product of the array is "_PROD
 KILL SUM,PROD,POS
 QUIT


using System;
using System.Console;
using System.Collections.Generic;
using Nemerle.Collections;

module SumProd
{
    Sum[T] (nums : T) : int
      where T : IEnumerable[int]
    {
        nums.FoldLeft(0, _+_)
    }

    Product[T] (nums : T) : int
      where T : IEnumerable[int]
    {
        nums.FoldLeft(1, _*_)
    }

    Main() : void
    {
        def arr = array[1, 2, 3, 4, 5];
        def lis = [1, 2, 3, 4, 5];

        def suml = Sum(lis);
        def proda = Product(arr);

        WriteLine("Sum is: {0}\tProduct is: {1}", suml, proda);
    }
}


/* NetRexx */

options replace format comments java crossref savelog symbols binary

harry = [long 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

sum = long 0
product = long 1
entries = Rexx ''

loop n_ = int 0 to harry.length - 1
  nxt = harry[n_]
  entries = entries nxt
  sum = sum + nxt
  product = product * nxt
  end n_

entries = entries.strip

say 'Sum and product of' entries.changestr(' ', ',')':'
say '     Sum:' sum
say ' Product:' product

return


(setq a '(1 2 3 4 5))
(apply + a)
(apply * a)


var xs = [1, 2, 3, 4, 5, 6]

var sum, product: int

product = 1

for x in xs:
  sum += x
  product *= x


- (float) sum:(NSMutableArray *)array
{
	int i, sum, value;
	sum = 0;
	value = 0;

	for (i = 0; i < [array count]; i++) {
		value = [[array objectAtIndex: i] intValue];
		sum += value;
	}

	return suml;
}


a=.my_array~new(20)
do i=1 To 20
  a[i]=i
  End
s=a~makestring((LINE),',')
Say s
Say '    sum='a~sum
Say 'product='a~prod
::class my_array subclass array
::method sum
sum=0
Do i=1 To self~dimension(1)
  sum+=self[i]
  End
Return sum
::method prod
Numeric Digits 30
prod=1
Do i=1 To self~dimension(1)
  prod*=self[i]
  End
Return prod


declare
  Xs = [1 2 3 4 5]
  Sum = {FoldL Xs Number.'+' 0}
  Product = {FoldL Xs Number.'*' 1}
in
  {Show Sum}
  {Show Product}


my @list = ( 1, 2, 3 );

my ( $sum, $prod ) = ( 0, 1 );
$sum  += $_ foreach @list;
$prod *= $_ foreach @list;


sequence s = {1,2,3,4,5}
printf(1,"sum is %d\n",sum(s))
printf(1,"prod is %d\n",product(s))


include ..\Utilitys.pmt

( 1 2 3 4 5 )

dup sum "sum is " print print nl

1 swap
len for
    get rot * swap
endfor
drop

"mult is " print print nl


$array = array(1,2,3,4,5,6,7,8,9);
echo array_sum($array);
echo array_product($array);


go =>
  L = 1..10,
  println(sum=sum(L)),
  println(prod=prod(L)),
  nl,
  println(sum_reduce=reduce(+,L)),
  println(prod_reduce=reduce(*,L)),
  println(sum_reduce=reduce(+,L,0)),
  println(prod_reduce=reduce(*,L,1)),
  nl,
  println(sum_fold=fold(+,0,L)),
  println(prod_fold=fold(*,1,L)),
  nl,
  println(sum_rec=sum_rec(L)),
  println(prod_rec=prod_rec(L)),

  nl.

% recursive variants
sum_rec(List) = Sum =>
  sum_rec(List,0,Sum).
sum_rec([],Sum0,Sum) =>
  Sum=Sum0.
sum_rec([H|T], Sum0,Sum) =>
  sum_rec(T, H+Sum0,Sum).

prod_rec(List) = Prod =>
  prod_rec(List,1,Prod).
prod_rec([],Prod0,Prod) =>
  Prod=Prod0.
prod_rec([H|T], Prod0,Prod) =>
  prod_rec(T, H*Prod0,Prod).


(let Data (1 2 3 4 5)
   (cons
      (apply + Data)
      (apply * Data) ) )


declare A(10) fixed binary static initial
   (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

put skip list (sum(A));
put skip list (prod(A));


An element is a thing with a number.

To find a sum and a product of some elements:
Put 0 into the sum.
Put 1 into the product.
Get an element from the elements.
Loop.
If the element is nil, exit.
Add the element's number to the sum.
Multiply the product by the element's number.
Put the element's next into the element.
Repeat.

To make some example elements:
If a counter is past 10, exit.
Allocate memory for an element.
Put the counter into the element's number.
Append the element to the example.
Repeat.

A product is a number.

To run:
Start up.
Make some example elements.
Find a sum and a product of the example elements.
Destroy the example elements.
Write "Sum: " then the sum on the console.
Write "Product: " then the product on the console.
Wait for the escape key.
Shut down.

A sum is a number.


lvars i, sum = 0, prod = 1, ar = {1 2 3 4 5 6 7 8 9};
for i from 1 to length(ar) do
    ar(i) + sum -> sum;
    ar(i) * prod -> prod;
endfor;


/sumandproduct
{
/x exch def
/sum 0 def
/prod 0 def
/i 0 def
x length 0 eq
{
}
{
/prod prod 1 add def
x length{
/sum sum x i get add def
/prod prod x i get mul def
/i i 1 add def
}repeat
}ifelse
sum ==
prod ==
}def


function Get-Sum ($a) {
    return ($a | Measure-Object -Sum).Sum
}


sum([],0).
sum([H|T],X) :- sum(T,Y), X is H + Y.
product([],1).
product([H|T],X) :- product(T,Y), X is H * X.


Dim MyArray(9)
Define a, sum=0, prod=1

For a = 0 To ArraySize(MyArray())     ; Create a list of some random numbers
  MyArray(a) = 1 + Random(9)          ; Insert a number [1...10] in current element
Next

For a = 0 To ArraySize(MyArray())     ; Calculate Sum and Product of this Array
  sum  + MyArray(a)
  prod * MyArray(a)
Next

Debug "The sum is " + Str(sum)        ; Present the results
Debug "Product is " + Str(prod)


numbers = [1, 2, 3]
total = sum(numbers)

product = 1
for i in numbers:
    product *= i


DIM array(1 TO 5)
DATA 1, 2, 3, 4, 5
FOR index = LBOUND(array) TO UBOUND(array)
    READ array(index)
NEXT index

LET sum = 0
LET prod = 1
FOR index = LBOUND(array) TO UBOUND(array)
    LET sum = sum + array(index)
    LET prod = prod * array(index)
NEXT index
PRINT "The sum is "; sum
PRINT "and the product is "; prod
END


[ 0 swap witheach + ] is sum ( [ --> n )

[ 1 swap witheach * ] is product ( [ --> n )


rebol [
    Title: "Sum and Product"
    URL: http://rosettacode.org/wiki/Sum_and_product_of_array
]

; Simple:

sum: func [a [block!] /local x] [x: 0  forall a [x: x + a/1]  x]

product: func [a [block!] /local x] [x: 1  forall a [x: x * a/1]  x]

; Way too fancy:

redux: func [
	"Applies an operation across an array to produce a reduced value."
	a [block!] "Array to operate on."
	op [word!] "Operation to perform."
	/init x    "Initial value (default 0)."
][if not init [x: 0]  forall a [x: do compose [x (op) (a/1)]]  x]

rsum: func [a [block!]][redux a '+]

rproduct: func [a [block!]][redux/init a '* 1]

; Tests:

assert: func [code][print [either do code ["  ok"]["FAIL"]  mold code]]

print "Simple dedicated functions:"
assert [55      = sum [1 2 3 4 5 6 7 8 9 10]]
assert [3628800 = product [1 2 3 4 5 6 7 8 9 10]]

print [crlf "Fancy reducing function:"]
assert [55      = rsum [1 2 3 4 5 6 7 8 9 10]]
assert [3628800 = rproduct [1 2 3 4 5 6 7 8 9 10]]


Red [
    red-version: 0.6.4
    description: "Find the sum and product of an array of numbers."
]

product: function [
    "Returns the product of all values in a block."
    values [any-list! vector!]
][
    result: 1
    foreach value values [result: result * value]
    result
]

a: [1 2 3 4 5 6 7 8 9 10]
print a
print ["Sum:" sum a]
print ["Product:" product a]


/*REXX program adds and multiplies   N   elements of a (populated)  array  @. */
numeric digits 200                     /*200 decimal digit #s  (default is 9).*/
parse arg N .;  if N==''  then N=20    /*Not specified?  Then use the default.*/

          do j=1  for N                /*build array of  N  elements (or 20?).*/
          @.j=j                        /*set 1st to 1, 3rd to 3, 8th to 8 ··· */
          end   /*j*/
sum=0                                  /*initialize  SUM  (variable) to zero. */
prod=1                                 /*initialize  PROD (variable) to unity.*/
          do k=1  for N
          sum  = sum  + @.k            /*add the element to the running total.*/
          prod = prod * @.k            /*multiply element to running product. */
          end   /*k*/                  /* [↑]  this pgm:  same as N factorial.*/

say '     sum of '     m     " elements for the  @  array is: "     sum
say ' product of '     m     " elements for the  @  array is: "     prod
                                       /*stick a fork in it,  we're all done. */


aList = 1:10   nSum=0  nProduct=0
for x in aList nSum += x nProduct *= x next
See "Sum = " + nSum + nl
See "Product = " + nProduct + nl


arr = [1,2,3,4,5]     # or ary = *1..5, or ary = (1..5).to_a
p sum = arr.inject(0) { |sum, item| sum + item }
# => 15
p product = arr.inject(1) { |prod, element| prod * element }
# => 120


dim array(100)
for i = 1 To 100
    array(i) = rnd(0) * 100
next i

product = 1
for i = 0 To 19
    sum     = (sum + array(i))
    product = (product * array(i))
next i

Print "    Sum is ";sum
Print "Product is ";product


fn main() {
    let arr = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];

    // using fold
    let sum = arr.iter().fold(0i32, |a, &b| a + b);
    let product = arr.iter().fold(1i32, |a, &b| a * b);
    println!("the sum is {} and the product is {}", sum, product);

    // or using sum and product
    let sum = arr.iter().sum::<i32>();
    let product = arr.iter().product::<i32>();
    println!("the sum is {} and the product is {}", sum, product);
}


data _null_;
   array a{*} a1-a100;
   do i=1 to 100;
      a{i}=i*i;
   end;
   b=sum(of a{*});
   put b c;
run;


class MAIN is
  main is
    a :ARRAY{INT} := |10, 5, 5, 20, 60, 100|;
    sum, prod :INT;
    loop sum := sum + a.elt!; end;
    prod := 1;
    loop prod := prod * a.elt!; end;
    #OUT + sum + " " + prod + "\n";
  end;
end;


val seq = Seq(1, 2, 3, 4, 5)
val sum = seq.foldLeft(0)(_ + _)
val product = seq.foldLeft(1)(_ * _)


const func integer: sumArray (in array integer: valueArray) is func
  result
    var integer: sum is 0;
  local
    var integer: value is 0;
  begin
    for value range valueArray do
      sum +:= value;
    end for;
  end func;

const func integer: prodArray (in array integer: valueArray) is func
  result
    var integer: prod is 1;
  local
    var integer: value is 0;
  begin
    for value range valueArray do
      prod *:= value;
    end for;
  end func;


numbers := [1 2 3 4 5 6 7 8 9];
print(+/ numbers, */ numbers);


#(1 2 3 4 5) reduce: [:sum :number | sum + number]
#(1 2 3 4 5) reduce: [:product :number | product * number]


#(1 2 3 4 5) inject: 0 into: [:sum :number | sum + number]
#(1 2 3 4 5) inject: 1 into: [:product :number | product * number]


          t = table()
* read the integer from the std. input
init_tab  t<x = x + 1> = trim(input)    :s(init_tab)
          product = 1
          sum = 0

* counting backwards to 1
loop      i = t< x = ?gt(x,1) x - 1>	:f(out)
          sum = sum + i
          product = product * i         :(loop)
out       output = "Sum:  " sum
          output = "Prod: " product
end


(* ints *)
val a = Array.fromList [1, 2, 3, 4, 5];
Array.foldl op+ 0 a;
Array.foldl op* 1 a;
(* reals *)
val a = Array.fromList [1.0, 2.0, 3.0, 4.0, 5.0];
Array.foldl op+ 0.0 a;
Array.foldl op* 1.0 a;


let a = [1, 2, 3, 4, 5]
println(a.reduce(0, +)) // prints 15
println(a.reduce(1, *)) // prints 120

println(reduce(a, 0, +)) // prints 15
println(reduce(a, 1, *)) // prints 120


set arr [list 3 6 8]
set sum [expr [join $arr +]]
set prod [expr [join $arr *]]


4 cells is-array foo

212 1 foo array.put
51 2 foo array.put
12 3 foo array.put
91 4 foo array.put

[ ( array size -- sum )
  >r 0 r> 0 [ over i swap array.get + ] countedLoop nip ] is sum-array

 ( product )
reset 1 4 0 [ i foo array.get * ] countedLoop .


DIM array(1 TO 5)
DATA 1, 2, 3, 4, 5
FOR index = LBOUND(array) TO UBOUND(array)
    READ array(index)
NEXT index

LET sum = 0
LET prod = 1
FOR index = LBOUND(array) TO UBOUND(array)
    LET sum = sum + array(index)
    LET prod = prod * array(index)
NEXT index
PRINT "The sum is "; sum
PRINT "and the product is "; prod
END


$$ MODE TUSCRIPT
list="1'2'3'4'5"
sum=SUM(list)
PRINT "    sum: ",sum

product=1
LOOP l=list
product=product*l
ENDLOOP
PRINT "product: ",product


sum=0
prod=1
list="1 2 3"
for n in $list
do sum="$(($sum + $n))"; prod="$(($prod * $n))"
done
echo $sum $prod


prod() {
   (read B; res=$1; test -n "$B" && expr $res \* $B || echo $res)
}

sum() {
   (read B; res=$1; test -n "$B" && expr $res + $B || echo $res)
}

fold() {
   (func=$1; while read a ; do fold $func | $func $a ; done)
}

(echo 3; echo 1; echo 4;echo 1;echo 5;echo 9) |
  tee >(fold sum) >(fold prod) > /dev/null


declare int<> stream
append 34 76 233 8 2 734 56 stream

# outputs 1143
out (+ stream) endl console

# outputs 3.95961079808E11
out (* stream) endl console


[sp dup 0 [+] fold 'product=' put puts 1 [*] fold 'sum=' put puts].


void main() {
  int sum = 0, prod = 1;
  int[] data = { 1, 2, 3, 4 };
  foreach (int val in data) {
    sum  += val;
    prod *= val;
  }
  print(@"sum: $(sum)\nproduct: $(prod)");
}


Sub Demo()
Dim arr
    arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    Debug.Print "sum : " & Application.WorksheetFunction.Sum(arr)
    Debug.Print "product : " & Application.WorksheetFunction.Product(arr)
End Sub


Function sum_and_product(arr)
	sum = 0
	product = 1
	For i = 0 To UBound(arr)
		sum = sum + arr(i)
		product = product * arr(i)
	Next
	WScript.StdOut.Write "Sum: " & sum
	WScript.StdOut.WriteLine
	WScript.StdOut.Write "Product: " & product
	WScript.StdOut.WriteLine
End Function

myarray = Array(1,2,3,4,5,6)
sum_and_product(myarray)


Module Program
    Sub Main()
        Dim arg As Integer() = {1, 2, 3, 4, 5}
        Dim sum = arg.Sum()
        Dim prod = arg.Aggregate(Function(runningProduct, nextFactor) runningProduct * nextFactor)
    End Sub
End Module


def (sum_prod nums)
  (list (+ @nums) (* @nums))


let a => import 'arrays';
let s => import 'stream';

let sum array => a.stream array -> s.reduce 0 +;
let prod array => a.stream prod -> s.reduce 1 *;


@sum [1 2 3 4] ; returns 10
@prod [1 2 3 4] ; returns 24


import "/math" for Nums
var a = [7, 10, 2, 4, 6, 1, 8, 3, 9, 5]
System.print("Array   : %(a)")
System.print("Sum     : %(Nums.sum(a))")
System.print("Product : %(Nums.prod(a))")


<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" />

  <xsl:template name="sum-prod">
    <xsl:param name="values" />
    <xsl:param name="sum"  select="0" />
    <xsl:param name="prod" select="1" />
    <xsl:choose>
      <xsl:when test="not($values)">
        <xsl:text>
Sum: </xsl:text>
        <xsl:value-of select="$sum" />
        <xsl:text>
Product: </xsl:text>
        <xsl:value-of select="$prod" />
      </xsl:when>
      <xsl:otherwise>
        <xsl:call-template name="sum-prod">
          <xsl:with-param name="values" select="$values[position() > 1]" />
          <xsl:with-param name="sum"  select="$sum  + $values[1]" />
          <xsl:with-param name="prod" select="$prod * $values[1]" />
        </xsl:call-template>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="/">
     <xsl:text>
Sum (built-in): </xsl:text>
    <xsl:value-of select="sum(//price)" />

    <xsl:call-template name="sum-prod">
      <xsl:with-param name="values" select="//price" />
    </xsl:call-template>
  </xsl:template>
</xsl:stylesheet>


dim array(5)
data 1, 2, 3, 4, 5
for index = 1 to arraysize(array(), 1)
    read array(index)
next index

sum = 0
prod = 1
for index = 1 to arraysize(array(), 1)
    sum = sum + array(index)
    prod = prod * array(index)
next index
print "The sum is ", sum            //15
print "and the product is ", prod   //120
end


fcn sum(vals){vals.reduce('+,0)}
fcn product(vals){vals.reduce('*,1)}


program: sum_and_product
  case: 1
    input: [3,5]
    output: [8,15]
  case: 2
    input: [2,3,4]
    output: [9,24]


V key = ‘]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\C1yxJ’

F encode(s)
   V r = ‘’
   L(c) s
      r ‘’= :key[c.code - 32]
   R r

F decode(s)
   V r = ‘’
   L(c) s
      r ‘’= Char(code' :key.index(c) + 32)
   R r

V s = ‘The quick brown fox jumps over the lazy dog, who barks VERY loudly!’
V enc = encode(s)
print(‘Encoded:  ’enc)
print(‘Decoded:  ’decode(enc))


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";
   Key :     constant String := "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN";
   My_Map : Character_Mapping;
   Input, Output : File_Type;
   Buffer        : Character;
begin
   declare
      use Ada.Text_IO;
   begin
      if Argument_Count /= 1 then
	 Put_Line("Usage: " & Command_Name & " <encode|decode>");
      else
	 if Argument(1) = "encode" then
	    My_Map := To_Mapping(From => Alphabet, To => Key);
	 elsif Argument(1) = "decode" then
	    My_Map := To_Mapping(From => Key, To => Alphabet);
	 else
	    Put_Line("Unrecognised Argument: " & Argument(1));
	    return;
	 end if;
      end if;
   end;
   Open       (File => Input,  Mode => In_File,  Name => "input.txt");
   Create     (File => Output, Mode => Out_File, Name => "output.txt");
   loop
      Read  (File => Input,  Item => Buffer);
      Buffer := Value(Map => My_Map, Element => Buffer);
      Write (File => Output, Item => Buffer);
   end loop;
exception
   when Char_IO.End_Error =>
      if Is_Open(Input) then
         Close (Input);
      end if;
      if Is_Open(Output) then
         Close (Output);
      end if;
end Cipher;


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 ->
        'bs ++ to :string to :char (index key ch)+32
    return join bs
]

s: "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"

enc: encode s
print ["encoded:" enc]
print ["decoded:" decode enc]


#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,"r");
	FILE* outFile;

	int i,len, diff = (flag==ENCRYPT)?(int)cipherKey - (int)plainKey:(int)plainKey - (int)cipherKey;
	wchar_t str[1000], *outStr;
	char* outFileName = (char*)malloc((strlen(fileName)+5)*sizeof(char));

	sprintf(outFileName,"%s_%s",fileName,(flag==ENCRYPT)?"ENC":"DEC");

	outFile = fopen(outFileName,"w");

	while(fgetws(str,1000,inpFile)!=NULL){
		len = wideStrLen(str);

		outStr = (wchar_t*)malloc((len + 1)*sizeof(wchar_t));

		for(i=0;i<len;i++){
			if((int)str[i]>=ALPHA && (int)str[i]<=OMEGA && flag == ENCRYPT)
				outStr[i] = (wchar_t)((int)str[i]+diff);
			 else if((int)str[i]-diff>=ALPHA && (int)str[i]-diff<=OMEGA && flag == DECRYPT)
				outStr[i] = (wchar_t)((int)str[i]-diff);
			else
				outStr[i] = str[i];
		}
		outStr[i]=str[i];

		fputws(outStr,outFile);

		free(outStr);
	}

	fclose(inpFile);
	fclose(outFile);
}

int main(int argC,char* argV[]){
	if(argC!=5)
		printf("Usage : %s <file name, plain key, cipher key, action (E)ncrypt or (D)ecrypt>",argV[0]);
	else{
		processFile(argV[1],argV[2][0],argV[3][0],(argV[4][0]=='E'||argV[4][0]=='e')?ENCRYPT:DECRYPT);

		printf("File %s_%s has been written to the same location as input file.",argV[1],(argV[4][0]=='E'||argV[4][0]=='e')?"ENC":"DEC");
	}

	return 0;
}


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);
            doEncDec("enc.txt", "dec.txt", false);
            Console.WriteLine("Done");
            Console.ReadKey();
        }
        static void doEncDec(String source, String target, bool IsEncrypt)
        {
            ITransform trans;

            if (IsEncrypt)
                trans = new Encrypt();
            else
                trans = new Decrypt();

            FileInfo sfi = new FileInfo(source);
            FileStream sstream = sfi.OpenRead();
            StreamReader sr = new StreamReader(sstream);

            FileInfo tfi = new FileInfo(target);
            FileStream tstream = tfi.OpenWrite();
            TransformWriter tw = new TransformWriter(tstream, trans);
            StreamWriter sw = new StreamWriter(tw);

            String line;
            while ((line = sr.ReadLine()) != null)
                sw.WriteLine(line);
            sw.Close();
        }
    }
    public interface ITransform
    {
        byte transform(byte ch);
    }
    public class Encrypt : ITransform
    {
        const String str = "xyfagchbimpourvnqsdewtkjzl";
        byte ITransform.transform(byte ch)
        {
            if (char.IsLower((char)ch))
                ch = (byte)str[ch - (byte)'a'];
            return ch;
        }
    }
    class Decrypt : ITransform
    {
        const String str = "xyfagchbimpourvnqsdewtkjzl";
        byte ITransform.transform(byte ch)
        {
            if (char.IsLower((char)ch))
                ch = (byte)(str.IndexOf((char)ch) + 'a');
            return ch;
        }
    }
    class TransformWriter : Stream, IDisposable
    {
        private Stream outs;
        private ITransform trans;

        public TransformWriter(Stream s, ITransform t)
        {
            this.outs = s;
            this.trans = t;
        }

        public override bool CanRead
        {
            get { return false; }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanWrite
        {
            get { return true; }
        }
        public override void Flush()
        {
            outs.Flush();
        }

        public override long Length
        {
            get { return outs.Length; }
        }
        public override long Position
        {
            get
            {
                return outs.Position;
            }
            set
            {
                outs.Position = value;
            }
        }
        public override long Seek(long offset, SeekOrigin origin)
        {
            return outs.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            outs.SetLength(value);
        }

        public override void Write(byte[] buf, int off, int len)
        {
            for (int i = off; i < off + len; i++)
                buf[i] = trans.transform(buf[i]);
            outs.Write(buf, off, len);
        }

        void IDisposable.Dispose()
        {
            outs.Dispose();
        }

        public override void Close()
        {
            outs.Close();
        }

        public override int Read(byte[] cbuf, int off, int count)
        {
            return outs.Read(cbuf, off, count);
        }
    }
}


#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( "" == keyBuffer ) return false;

        outName = f;
        outName.insert( outName.find_first_of( "." ), "_out" );

        switch( e[0] ) {
            case 'e': return encode();
            case 'd': return decode();
        }
        return false;
    }
private:
    bool encode() {
        size_t idx, len = keyBuffer.length() >> 1;
        for( std::string::iterator i = fileBuffer.begin(); i != fileBuffer.end(); i++ ) {
            idx = keyBuffer.find_first_of( *i );
            if( idx < len ) outBuffer.append( 1, keyBuffer.at( idx + len ) );
            else outBuffer.append( 1, *i );
        }
        return saveOutput();
    }
    bool decode() {
        size_t idx, l = keyBuffer.length(), len = l >> 1;
        for( std::string::iterator i = fileBuffer.begin(); i != fileBuffer.end(); i++ ) {
            idx = keyBuffer.find_last_of( *i );
            if( idx >= len && idx < l ) outBuffer.append( 1, keyBuffer.at( idx - len ) );
            else outBuffer.append( 1, *i );
        }
        return saveOutput();
    }
    bool saveOutput() {
        std::ofstream o( outName.c_str() );
        o.write( outBuffer.c_str(), outBuffer.size() );
        o.close();
        return true;
    }
    std::string readFile( std::string fl ) {
        std::string buffer = "";
        std::ifstream f( fl.c_str(), std::ios_base::in );
        if( f.good() ) {
            buffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );
            f.close();
        }
        return buffer;
    }
    std::string fileBuffer, keyBuffer, outBuffer, outName;
};

int main( int argc, char* argv[] ) {
    if( argc < 4 ) {
        std::cout << "<d or e>\tDecrypt or Encrypt\n<filename>\tInput file, the output file will have"
        "'_out' added to it.\n<key>\t\tfile with the key to encode/decode\n\n";
    } else {
        cipher c;
        if( c.work( argv[1], argv[2], argv[3] ) ) std::cout << "\nFile successfully saved!\n\n";
        else std::cout << "Something went wrong!\n\n";
    }
    return 0;
}


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 into another output/encrypted file and then again convert
 that output/encrypted file into original/decrypted file. This
 type of Encryption/Decryption scheme is often called a
 Substitution Cipher.`;

void main() {
    auto enc = encode(text);
    writeln("Encoded: ", enc);
    writeln;
    writeln("Decoded: ", decode(enc));
}

enum FORWARD = "[email protected]#E$F%G^H&I*J(K)L+M=N[O]P{Q}R<S>T/U?V:W;X.Y,Z a\tbcdefghijkl\nmnopqrstuvwxyz";
auto encode(string input) {
    return tr(input, FORWARD, REVERSE);
}

enum REVERSE = "VsciBjedgrzy\nHalvXZKtUP um\tGf?I/w>J<x.q,OC:F;R{A]p}n[D+h=Q)W(o*b&L^k%E$S#[email protected]!T~N";
auto decode(string input) {
    return tr(input, REVERSE, FORWARD);
}


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
    "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"

SYMBOL: key

STRING: usage
Usage:
  substitution
  <encode|decode>
  input-file
  output-file
  [key-file]  (Optional -- for custom alphabet keys.)

Example:
  substitution encode my-poem.txt my-encoded-poem.txt
;

: check-args ( seq -- ? )
    {
        [ length 3 4 between? not ]
        [ first qw{ encode decode } member? not ]
    } 1|| [ usage print f ] [ t ] if ;

: init-key ( seq -- )
    dup length 4 = [ last utf8 file-contents ]
    [ drop default-key ] if key set ;

: >sub-map ( seq -- assoc )
    [ alphabet key get ] dip first "encode" = [ swap ] unless
    zip >hashtable ;

: encipher ( seq assoc -- newseq )
    [ dupd at dup [ nip ] [ drop ] if ] curry { } map-as ;

: substitute ( seq -- )
    { [ init-key ] [ second ] [ >sub-map ] [ third ] } cleave
    [ utf8 file-contents ] [ encipher ]
    [ utf8 set-file-contents ] tri* ;

: main ( -- )
    command-line get dup check-args [ substitute ] [ drop ] if ;

MAIN: main


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

  open(out_unit, file="encrypted.txt", iostat=ios)
  if (ios /= 0) then
    write(*,*) "Error opening encrypted.txt file"
    stop
  end if

! Encryption
  do
    read(in_unit, "(a)", iostat=ios) line
    if (ios > 0) then
      write(*,*) "Error reading plain.txt file"
      stop
    else if (ios == eof) then
      exit
    end if

    call cipher(trim(line))
    write(out_unit, "(a)", iostat=ios) trim(line)
    if (ios /= 0) then
      write(*,*) "Error writing encrypted.txt file"
      stop
    end if
  end do

  close(in_unit)
  close(out_unit)

  open(in_unit, file="encrypted.txt",  iostat=ios)
  if (ios /= 0) then
    write(*,*) "Error opening encrypted.txt file"
    stop
  end if

  open(out_unit, file="decrypted.txt", iostat=ios)
  if (ios /= 0) then
    write(*,*) "Error opening decrypted.txt file"
    stop
  end if

! Decryption
  do
    read(in_unit, "(a)", iostat=ios) line
    if (ios > 0) then
      write(*,*) "Error reading encrypted.txt file"
      stop
    else if (ios == eof) then
      exit
    end if

    call cipher(trim(line))
    write(out_unit, "(a)", iostat=ios) trim(line)
    if (ios /= 0) then
      write(*,*) "Error writing decrypted.txt file"
      stop
    end if
  end do

  close(in_unit)
  close(out_unit)

contains

subroutine cipher(text)
  character(*), intent(in out) :: text
  integer :: i

! Substitutes A -> Z, B -> Y ... Y -> B, Z -> A and ditto for lower case
! works for both encryption and decryption

  do i = 1, len(text)
    select case(text(i:i))
      case ('A':'Z')
        text(i:i) = achar(155 - iachar(text(i:i)))
      case ('a':'z')
        text(i:i) = achar(219 - iachar(text(i:i)))
    end select
  end do
end subroutine

end program


' 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 As #1
   If err > 0 Then
     Print "Unable to open input file"
     Sleep
     End
   End If
   Dim As String alpha, key
   If encrypt Then
     alpha = string1 : key = string2
   Else
     alpha = string2 : key = string1
   End If
   Open outputFile For Output As #2
   Dim s As String
   Dim p As Integer
   While Not Eof(1)
     Line Input #1, s
     For i As Integer = 0 To Len(s) - 1
       If (s[i] >= 65 AndAlso s[i] <= 90) OrElse (s[i] >= 97 AndAlso s[i] <= 122) Then
         p =  Instr(alpha, Mid(s, i + 1, 1)) - 1
         s[i] = key[p]
       End If
     Next
     Print #2, s
   Wend
   Close #1 : Close #2
End Sub

process "plain.txt", "encrypted.txt", true
process "encrypted.txt", "decrypted.txt", false
Print
Print "Press any key to quit"
Sleep


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)
}

func decode(s string) string {
    bs := []byte(s)
    for i := 0; i < len(bs); i++ {
        bs[i] = byte(strings.IndexByte(key, bs[i]) + 32)
    }
    return string(bs)
}

func main() {
    s := "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
    enc := encode(s)
    fmt.Println("Encoded: ", enc)
    fmt.Println("Decoded: ", decode(enc))
}


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" THEN
190   INPUT PROMPT "File name: ":NAME$
200   IF OPENFILE(NAME$) THEN CALL CHIPER(1)
210 ELSE
220   IF OPENFILE("Encrypte.txt") THEN CALL CHIPER(2)
230 END IF
240 DEF OPENFILE(N$)
250   LET OPENFILE=0
260   WHEN EXCEPTION USE OPENERROR
270     OPEN #1:N$
280   END WHEN
290   LET OPENFILE=-1
300 END DEF
310 DEF CHIPER(FUNC)
320   LET EOF=0
330   WHEN EXCEPTION USE OPENERROR
340     IF FUNC=1 THEN
350       OPEN #2:"Encrypte.txt" ACCESS OUTPUT
360       LET OUTP=2
370     ELSE
380       OPEN #2:"Decrypte.txt" ACCESS OUTPUT
390       LET OUTP=1
400     END IF
410   END WHEN
420   WHEN EXCEPTION USE IOERROR
430     DO
440       GET #1:K$
450       IF UCASE$(K$)>="A" AND UCASE$(K$)<="Z" THEN
460         PRINT #2:ST$(OUTP)(POS(ST$(FUNC),K$));
470       ELSE
480         PRINT #2:K$;
490       END IF
500     LOOP UNTIL EOF
510   END WHEN
520   HANDLER IOERROR
530     IF EXTYPE<>9228 THEN PRINT EXSTRING$(EXTYPE)
540     CLOSE #2
550     CLOSE #1
560     LET EOF=1
570   END HANDLER
580 END DEF
590 HANDLER OPENERROR
600   PRINT EXSTRING$(EXTYPE)
610   END
620 END HANDLER


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 alphabet)

shuffle :: Int -> [a] -> [a]
shuffle n xs = iterate go xs !! n
  where
    go [] = []
    go xs = go (drop 2 xs) <> take 2 xs

convert :: Eq a => [(a, a)] -> [a] -> [a]
convert m = map (\x -> fromMaybe x (lookup x m))

runCommand :: Command -> String
runCommand (Cipher s)   = convert cipherMap s
runCommand (Decipher s) = convert (swap <$> cipherMap) s
runCommand Invalid = "Invalid arguments. Usage: simplecipher c|d <text>"

parseArgs :: [String] -> Command
parseArgs (x:y:xs)
  | x == "c" = Cipher y
  | x == "d" = Decipher y
  | otherwise = Invalid
parseArgs _ = Invalid

main :: IO ()
main = parseArgs <$> getArgs >>= putStrLn . runCommand


keysubst=: [`(a.i.])`(a."_)}
key=: 'Taehist' keysubst '[email protected]#$%^&'
enc=: a. {~ key i. ]
dec=: key {~ a. i. ]

   enc 'This is a test.'
!$%^ %^ @ &#^&.
   dec '!$%^ %^ @ &#^&.'
This is a test.


public class SubstitutionCipher {

    final static String key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"
            + "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";

    static 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 into another output/encrypted file and then again convert "
            + "that output/encrypted file into original/decrypted file. This "
            + "type of Encryption/Decryption scheme is often called a "
            + "Substitution Cipher.";

    public static void main(String[] args) {
        String enc = encode(text);
        System.out.println("Encoded: " + enc);
        System.out.println("\nDecoded: " + decode(enc));
    }

    static String encode(String s) {
        StringBuilder sb = new StringBuilder(s.length());

        for (char c : s.toCharArray())
            sb.append(key.charAt((int) c - 32));

        return sb.toString();
    }

    static String decode(String s) {
        StringBuilder sb = new StringBuilder(s.length());

        for (char c : s.toCharArray())
            sb.append((char) (key.indexOf((int) c) + 32));

        return sb.toString();
    }
}


def key:
  "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";

def encode:
  (key|explode) as $key
  | explode as $exploded
  | reduce range(0;length) as $i ([];
        . + [$key[ $exploded[$i] - 32]] )
  | implode;

def decode:
  (key|explode) as $key
  | explode as $exploded
  | reduce range(0;length) as $i ([];
       $exploded[$i] as $c
       | . + [ $key | index($c) + 32] )
  | implode ;

def task:
  "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
   | encode as $encoded
   |"Encoded:  \($encoded)",
    "Decoded:  \($encoded|decode)" ;

task


module SubstitutionCiphers

using Compat

const key = "]kYV}(!7P\$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"

function encode(s::AbstractString)
    buf = IOBuffer()
    for c in s
        print(buf, key[Int(c) - 31])
    end
    return String(take!(buf))
end

function decode(s::AbstractString)
    buf = IOBuffer()
    for c in s
        print(buf, Char(findfirst(==(c), key) + 31))
    end
    return String(take!(buf))
end

end  # module SubstitutionCiphers


include ..\Utilitys.tlhy

" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
" VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
"A simple example"

:Encode %mode !mode
    %i %t
    $mode not [rot rot swap rot] if
    len [
        !i
        $i get swap !t
        rot swap find
        rot swap get
        $t swap $i set
    ] for
    $mode not [rot rot swap rot] if
;

dup ?
true Encode dup ?
false Encode ?

" " input


// version 1.0.6

object SubstitutionCipher {
    val key = "]kYV}(!7P\$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"

    fun encode(s: String): String {
        val sb = StringBuilder()
        for (c in s) sb.append(key[c.toInt() - 32])
        return sb.toString()
    }

    fun decode(s: String): String {
        val sb = StringBuilder()
        for (c in s) sb.append((key.indexOf(c) + 32).toChar())
        return sb.toString()
    }
}

fun main(args: Array<String>) {
    val s = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
    val enc = SubstitutionCipher.encode(s)
    println("Encoded:  $enc")
    println("Decoded:  ${SubstitutionCipher.decode(enc)}")
}


{def small_ascii {S.map fromCharCode {S.serie 33 122}}}
-> small_ascii

{S.length {small_ascii}} = 90

{def substitution

 {def substitution.r
  {lambda {:w :n :s :i}
   {if {> :i :n}
    then
    else {let { {:s :s} {:c {W.char2code {A.get :i :w}}}
              } {if {and {>= :c 33} {<= :c 122}}
                 then {W.code2char {+ 33 {% {+ :c {- :s 33}} 90}}}
                 else {if {= :c 248} then :c else}}
         }{substitution.r :w :n :s {+ :i 1}} }}}

 {lambda {:s :w}
  {let { {:s :s} {:w {S.replace \s by ` in :w}}
       } {S.replace `
                 by space
                 in {substitution.r {A.split :w}
                                    {- {W.length :w} 1}
                                    :s
                                    0}} }}}
-> substitution

1) intitial text:

{def txt
Veni, Vidi, Vici is a Latin phrase popularly attributed to Julius Caesar who, according to Appian, used the phrase
in a letter to the Roman Senate around 47 BC after he had achieved a quick victory in his short war against
Pharnaces II of Pontus at the Battle of Zela.
} -> txt

2) choose the shift:

{def shift 13}
-> shift // valid in [0...90] except 5 10 15 29 30 50 53 70 74

3) encoding the text

 {substitution {shift} {txt}}
-> cr!v9mcvqv9mcvpvmv&mnmYn'v!m#u%n&rm#"#(yn%y,mn''%vo('rqm'"mW(yv(&mPnr&n%m*u"9mnpp"%qv!tm'"mN##vn!9m(&rqm'urm#u%n&rmv!mnmyr''r%m'"m'urm_"zn!m r!n'rmn%"
(!qmADmOPmns'r%murmunqmnpuvr)rqmnm$(vpxm)vp'"%,mv!muv&m&u"%'m*n%mntnv!&'m]un%!npr&mVVm"sm]"!'(&mn'm'urmOn''yrm"smgryn;

4) decoding the text

 {substitution {- 90 {shift}} {substitution {shift} {txt}}}
-> Veni, Vidi, Vici is a Latin phrase popularly attributed to Julius Caesar who, according to Appian, used the phrase
in a letter to the Roman Senate around 47 BC after he had achieved a quick victory in his short war against
Pharnaces II of Pontus at the Battle of Zela.


-- Generate a random substitution cipher for ASCII characters 65 to 122
function randomCipher ()
    local cipher, rnd = {plain = {}, encoded = {}}
    for ascii = 65, 122 do
        table.insert(cipher.plain, string.char(ascii))
        table.insert(cipher.encoded, string.char(ascii))
    end
    for i = 1, #cipher.encoded do
        rnd = math.random(#cipher.encoded)
        cipher.encoded[i], cipher.encoded[rnd] = cipher.encoded[rnd], cipher.encoded[i]
    end
    return cipher
end

-- Encipher text using cipher.  Decipher if decode is true.
function encode (text, cipher, decode)
    local output, letter, found, source, dest = ""
    if decode then
        source, dest = cipher.encoded, cipher.plain
    else
        source, dest = cipher.plain, cipher.encoded
    end
    for pos = 1, #text do
        letter = text:sub(pos, pos)
        found = false
        for k, v in pairs(source) do
            if letter == v then
                output = output .. dest[k]
                found = true
                break
            end
        end
        if not found then output = output .. letter end
    end
    return output
end

-- Main procedure
math.randomseed(os.time())
local subCipher = randomCipher()
print("Cipher generated:")
print("\tPlain:", table.concat(subCipher.plain))
print("\tCoded:", table.concat(subCipher.encoded))
local inFile = io.open("C:\\ulua\\taskDescription.txt", "r")
local input = inFile:read("*all")
inFile:close()
local encoded = encode(input, subCipher)
print("\nEncoded file contents:")
print("\t" .. encoded)
print("\nAbove text deciphers to: ")
print("\t" .. encode(encoded, subCipher, true))


alphabet = "abcdefghijklmnopqrstuvwxyz".split("")
cipher = alphabet[0:]
cipher.shuffle
encode = {}
decode = {}
for i in alphabet.indexes
    encode[alphabet[i]] = cipher[i]
    decode[cipher[i]] = alphabet[i]
    encode[alphabet[i].upper] = cipher[i].upper
    decode[cipher[i].upper] = alphabet[i].upper
end for

apply = function(map, s)
    chars = s.split("")
    for i in chars.indexes
        if map.hasIndex(chars[i]) then chars[i] = map[chars[i]]
    end for
    return chars.join("")
end function

msg = "Now is the time for all good men (and women) to come together."
secretCode = apply(encode, msg)
print secretCode
print apply(decode, secretCode)


import sequtils, strutils

proc encrypt(key: seq[char]; msg: string): string =
  result.setLen(msg.len)
  for i, c in msg:
    result[i] = key[ord(c) - 32]

proc decrypt(key: seq[char]; msg: string): string =
  result.setLen(msg.len)
  for i, c in msg:
    result[i] = chr(key.find(c) + 32)

when isMainModule:

  import random
  randomize()

  # Build a random key.
  var key = toSeq(32..126).mapIt(chr(it))   # All printable characters.
  key.shuffle()

  const Message = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
  let encrypted = key.encrypt(Message)
  let decrypted = key.decrypt(encrypted)

  echo "Key =       “$#”" % key.join()
  echo "Message =   “$#”" % Message
  echo "Encrypted = “$#”" % encrypted
  echo "Decrypted = “$#”" % decrypted