main() {
  var list = new List<int>.generate(1000, (i) => i + 1);

  num sum = 0;

  (list.map((x) => 1.0 / (x * x))).forEach((num e) {
    sum += e;
  });
  print(sum);
}


unit Form_SumOfASeries_Unit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TFormSumOfASeries = class(TForm)
    M_Log: TMemo;
    B_Calc: TButton;
    procedure B_CalcClick(Sender: TObject);
  private
    { Private-Deklarationen }
  public
    { Public-Deklarationen }
  end;

var
  FormSumOfASeries: TFormSumOfASeries;

implementation

{$R *.dfm}

function Sum_Of_A_Series(_from,_to:int64):extended;
begin
  result:=0;
  while _from<=_to do
  begin
    result:=result+1.0/(_from*_from);
    inc(_from);
  end;
end;

procedure TFormSumOfASeries.B_CalcClick(Sender: TObject);
begin
  try
    M_Log.Lines.Add(FloatToStr(Sum_Of_A_Series(1, 1000)));
  except
    M_Log.Lines.Add('Error');
  end;
end;

end.


function sumDigits(n) {
	n += ''
	for (var s=0, i=0, e=n.length; i<e; i+=1) s+=parseInt(n.charAt(i),36)
	return s
}
for (var n of [1, 12345, 0xfe, 'fe', 'f0e', '999ABCXYZ']) document.write(n, ' sum to ', sumDigits(n), '<br>')


tostring | explode | map(tonumber - 48) | add


sumdigits(n, base=10) = sum(digits(n, base))


(defn sum-mults [n & mults]
  (let [pred (apply some-fn
               (map #(fn [x] (zero? (mod x %))) mults))]
    (->> (range n) (filter pred) (reduce +))))

(println (sum-mults 1000 3 5))


Identification division.
Program-id. three-five-sum.

Data division.
Working-storage section.
01 ws-the-limit  pic 9(18) value 1000.
01 ws-the-number pic 9(18).
01 ws-the-sum    pic 9(18).
01 ws-sum-out    pic z(18).

Procedure division.
Main-program.
    Perform Do-sum
        varying ws-the-number from 1 by 1
        until ws-the-number = ws-the-limit.
    Move ws-the-sum to ws-sum-out.
    Display "Sum = " ws-sum-out.
    End-run.

Do-sum.
    If function mod(ws-the-number, 3) = zero
       or function mod(ws-the-number, 5) = zero
       then add ws-the-number to ws-the-sum.


var s : Float;
for var i := 1 to 1000 do
   s += 1 / Sqr(i);

PrintLn(s);


func Integer.SumSeries() {
    var ret = 0

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

    ret
}

var x = 1000
print(x.SumSeries())


pragma.enable("accumulator")
accum 0 for x in 1..1000 { _ + 1 / x ** 2 }


// version 1.1.0

const val digits = "0123456789abcdefghijklmnopqrstuvwxyz"

fun sumDigits(ns: String, base: Int): Int {
    val n = ns.toLowerCase().trim()
    if (base !in 2..36) throw IllegalArgumentException("Base must be between 2 and 36")
    if (n.isEmpty())    throw IllegalArgumentException("Number string can't be blank or empty")
    var sum = 0
    for (digit in n) {
        val index = digits.indexOf(digit)
        if (index == -1 || index >= base) throw IllegalArgumentException("Number string contains an invalid digit")
        sum += index
    }
    return sum
}

fun main(args: Array<String>) {
    val numbers = mapOf("1" to 10, "1234" to 10, "fe" to 16, "f0e" to 16, "1010" to 2, "777" to 8, "16xyz" to 36)
    println("The sum of digits is:")
    for ((number, base) in numbers) println("$number\tbase $base\t-> ${sumDigits(number, base)}")
}


define br => '<br />\n'

define sumdigits(int, base = 10) => {
	fail_if(#base < 2, -1, 'Base need to be at least 2')
	local(
		out		= integer,
		divmod
	)
	while(#int) => {
		 #divmod = #int -> div(#base)
		 #int = #divmod -> first
		 #out += #divmod -> second
	}
	return #out
}

sumdigits(1)
br
sumdigits(12345)
br
sumdigits(123045)
br
sumdigits(0xfe, 16)
br
sumdigits(0xf0e, 16)


(defun sum-3-5-slow (limit)
  (loop for x below limit
        when (or (zerop (rem x 3)) (zerop (rem x 5)))
          sum x))


MODULE Sum3_5;
IMPORT StdLog, Strings, Args;

PROCEDURE DoSum(n: INTEGER):INTEGER;
VAR
	i,sum: INTEGER;
BEGIN
	sum := 0;i := 0;
	WHILE (i < n) DO
		IF  (i MOD 3 = 0) OR (i MOD 5 = 0) THEN INC(sum,i) END;
		INC(i)
	END;
	RETURN sum
END DoSum;

PROCEDURE Compute*;
VAR
	params: Args.Params;
	i,n,res: INTEGER;
BEGIN
	Args.Get(params);
	Strings.StringToInt(params.args[0],n,res);
	StdLog.String("Sum: ");StdLog.Int(DoSum(n)); StdLog.Ln
END Compute;

END Sum3_5.


 [Sum of a series, Rosetta Code website.
  EDSAC program, Initial Orders 2.]
            ..PZ  [blank tape and terminator]

 [Library subroutine D6 - Division, accurate, fast.
  36 locations, working positons 6D and 8D.
  C(0D) := C(0D)/C(4D), where C(4D) <> 0, -1.]
            T56K
  [email protected]@[email protected]@[email protected]
  [email protected]@SDVDTDEFW1526D

 [Library subroutine P1 - Print positive number, no formatting or round-off.
  Prints number in 0D to n places of decimals, where n is specified by 'P n F'
  pseudo-order after subroutine call.  21 locations.]
            T92K
  [email protected]@[email protected]@[email protected]@[email protected]@EFU3FJFM1F

 [Custom subroutine to calculate 1/k^2 for a 17-bit integer k > 1.
  Input:  0F = k (with the usual scaling; actually k/(2^16).
  Output: 0D = 1/k^2.]
            T120K  GK
            A3F  [email protected]   [set up return to caller as usual]
            HF          [multiply register := k/(2^16)]
            VF          [acc := k/(2^16) squared]
   [At this point acc =(k^2)/(2^32). Now we switch to 35-bit
    arithmetic, in which integers are scaled by 2^(-34)]
            R1F         [shift acc 2 right to adjust scaling]
            T4D         [4D := k^2]
            TD          [set 0D := 0; clears "sandwich bit" between 0F and 1F]
            [email protected]  TF    [set 0D := 1 by setting 0F := 1]
            [email protected]  G56F   [call EDSAC library subroutine for division]
     [11]   ZF          [overwritten by jump back to caller]
     [12]   PD          [short constant 1]

 [Main program]
            T200K  GK   [load at even address because of long variable at 0]
      [0]   PF  PF      [build sum here]
      [2]   PD          [short constant 1]
      [3]   P500F       [short constant 1000]
      [4]   K2048F  #F  !F  @F  &F  [letters, figures, space, CR, LF]
      [9]   HF  IF  LF  [letters H, I, L (in letters mode)]
     [12]   QF  MF      [digit 1, dot (in figures mode)]
     [14]   PF          [variable k]

     [15]   T#@  [email protected] [email protected]            [sum := 0, k := 1]
     [18]   TF  [email protected]  [email protected]  [email protected]  TF  [inc k; pass new k to function in 0F]
            [email protected]  G120F              [call function; places 1/k^2 at 0D]
            AD  A#@  T#@             [add 1/k^2 into sum]
            [email protected]  [email protected]  [email protected]          [test for k = maximum, loop back if not]
            [email protected]  [email protected]  [email protected]  [email protected]  [email protected]  [email protected]  [email protected]  [email protected]  [email protected]  [email protected]  [print 'LO TO HI ']
            [email protected]  [email protected]  [email protected]          [print '1.']
            A#@  TD  [email protected]  G92F      [call subroutine to print decimal part]
            P10F                     [parameter for print subroutine; 10 decimal places]
            [email protected]  [email protected]                 [print CR, LF]

       [Sum in reverse order to confirm that the result is identical on EDSAC.
        Not much different from the above, so given in condensed form.]
            TFT#@[email protected]@[email protected]@G120FADA#@T#@[email protected]@[email protected]@TDA#@TD
            [email protected]@[email protected]@[email protected]@[email protected]@[email protected]@[email protected]@[email protected]@[email protected]@

     [89]   [email protected]  ZF                  [flush teleprinter buffer; stop]
            E15Z  PF                 [define entry point; enter with acc = 0]


on sum_digits (n, base)
  sum = 0
  repeat while n
    m = n / base
    sum = sum + n - m * base
    n = m
  end repeat
  return sum
end


function sumDigits n, base
    local numb
    if base is empty then put 10 into base
    repeat for each char d in n
        add baseConvert(d,base,10) to numb
    end repeat
    return numb
end sumDigits


make "digits "0123456789abcdefghijklmnopqrstuvwxyz

to digitvalue :digit
   output difference find [equal? :digit item ? :digits] iseq 1 count :digits 1
end

to sumdigits :number [:base 10]
  output reduce "sum map.se "digitvalue :number
end

foreach [1 1234 fe f0e] [print (se ? "-> sumdigits ?)]


function sum_digits(n, base)
    sum = 0
    while n > 0.5 do
        m = math.floor(n / base)
        digit = n - m * base
        sum = sum + digit
        n = m
    end
    return sum
end

print(sum_digits(1, 10))
print(sum_digits(1234, 10))
print(sum_digits(0xfe, 16))
print(sum_digits(0xf0e, 16))


include "cowgol.coh";

# sum multiples up to given input
interface SumMulTo(mul: uint32, to: uint32): (rslt: uint32);

# naive implementation
sub naiveSumMulTo implements SumMulTo is
    rslt := 0;
    var cur := mul;
    while cur < to loop
        rslt := rslt + cur;
        cur := cur + mul;
    end loop;
end sub;

# number theoretical implementation
sub fastSumMulTo implements SumMulTo is
    to := (to - 1)/mul;
    rslt := mul * to * (to + 1)/2;
end sub;

# sum multiples of 3 and 5 up to given number using given method
sub sum35(to: uint32, sum: SumMulTo): (rslt: uint32) is
    rslt := sum(3, to) + sum(5, to) - sum(15, to);
end sub;

print("Naive method: "); print_i32(sum35(1000, naiveSumMulTo)); print_nl();
print("Fast method:  "); print_i32(sum35(1000, fastSumMulTo)); print_nl();


def sum_3_5_multiples(n)
  (0...n).select { |i| i % 3 == 0 || i % 5 == 0 }.sum
end

puts sum_3_5_multiples(1000)


note
	description: "Compute the n-th term of a series"

class
	SUM_OF_SERIES_EXAMPLE

inherit
	MATH_CONST

create
	make

feature -- Initialization

	make
		local
			approximated, known: REAL_64
		do
			known := Pi^2 / 6

			approximated := sum_until (agent g, 1001)
			print ("%Nzeta function exact value: %N")
			print (known)
			print ("%Nzeta function approximated value: %N")
			print (approximated)
		end

feature -- Access

	g (k: INTEGER): REAL_64
			-- 'k'-th term of the serie
		require
			k_positive: k > 0
		do
			Result := 1 / (k * k)
		end

	sum_until (s: FUNCTION [ANY, TUPLE [INTEGER], REAL_64]; n: INTEGER): REAL_64
			-- sum of the 'n' first terms of 's'
		require
			n_positive: n > 0
			one_parameter: s.open_count = 1
		do
			Result := 0
			across 1 |..| n as it loop
				Result := Result + s.item ([it.item])
			end
		end

end


import system'routines;
import extensions;

public program()
{
    var sum := new Range(1, 1000).selectBy:(x => 1.0r / (x * x)).summarize(new Real());

    console.printLine:sum
}


sumDigits := proc( num )
	local digits, number_to_string, i;
	number_to_string := convert( num, string );
	digits := [ seq( convert( h, decimal, hex ), h in seq( parse( i ) , i in number_to_string ) ) ];
	return add( digits );
end proc:
sumDigits( 1234 );
sumDigits( "fe" );


import std.stdio, std.bigint;

BigInt sum35(in BigInt n) pure nothrow {
    static BigInt sumMul(in BigInt n, in int f) pure nothrow {
        immutable n1 = (f==n?n:(n - 1) ) / f;
        return f * n1 * (n1 + 1) / 2;
    }

    return sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15);
}

void main() {
    1.BigInt.sum35.writeln;
    3.BigInt.sum35.writeln;
    5.BigInt.sum35.writeln;
    1000.BigInt.sum35.writeln;
    (10.BigInt ^^ 20).sum35.writeln;
}


[ Sm Sn lm 1 - d ln % - d sm ln / ln lm + * 0k 2 / Ss Lm sx Ln sx Ls ]sm

[ d d d 3 r lmx r 5 r lmx + r 15 r lmx - ]ss

[ 27 P 91 P 65 P 27 P 91 P 50 P 50 P 67 P ]su

[ ll p lsx lux p ll 10 * d sl 1000000000000000000000 >d]sd

1 sl ldx


(defun series (n)
  (when (<= n 0)
    (user-error "n must be positive"))
  (apply #'+ (mapcar (lambda (k) (/ 1.0 (* k k))) (number-sequence 1 n))))

(format "%.10f" (series 1000)) ;=> "1.6439345667"


local
 open IntInf
in
 fun summDigits  base = ( fn 0 => 0 | n => n mod base + summDigits base (n div base ) )
end;

summDigits 10 1 ;
summDigits 10 1234 ;
summDigits 16 0xfe ;
summDigits 16 0xf0e ;
summDigits 4332489243570890023480923 0x8092eeac80923984098234098efad2109ce341000c3f0912527130  ;


MODULE SumOFDigits;
FROM STextIO IMPORT
  WriteString, WriteLn;
FROM SWholeIO IMPORT
  WriteInt;
FROM Conversions IMPORT
  StrBaseToLong;

PROCEDURE SumOfDigitBase(N: LONGCARD; Base: CARDINAL): CARDINAL;
VAR
  Tmp, LBase: LONGCARD;
  Digit, Sum : CARDINAL;
BEGIN
  Digit := 0;
  Sum   := 0;
  LBase := Base;
  WHILE N > 0 DO
    Tmp := N / LBase;
    Digit := N - LBase * Tmp;
    N := Tmp;
    INC(Sum, Digit);
  END;
  RETURN Sum;
END SumOfDigitBase;

VAR
  Num: LONGCARD;

BEGIN
  WriteString('   1 sums to ');
  WriteInt(SumOfDigitBase(1, 10), 1);
  WriteLn;
  WriteString('1234 sums to ');
  WriteInt(SumOfDigitBase(1234, 10), 1);
  WriteLn;
  IF StrBaseToLong('FE', 16, Num) THEN
    WriteString(' $FE sums to ');
    WriteInt(SumOfDigitBase(Num, 16), 1);
    WriteLn;
  END;
  IF StrBaseToLong('F0E', 16, Num) THEN
    WriteString('$F0E sums to ');
    WriteInt(SumOfDigitBase(Num, 16), 1);
    WriteLn;
  END;
  WriteString('MAX(LONGCARD) (in dec) sums to ');
  WriteInt(SumOfDigitBase(MAX(LONGCARD), 10), 1);
  WriteLn;
END SumOFDigits.


program sum35;

{$APPTYPE CONSOLE}

var
  sum: integer;
  i: integer;

function isMultipleOf(aNumber, aDivisor: integer): boolean;
begin
  result := aNumber mod aDivisor = 0
end;

begin
  sum := 0;
  for i := 3 to 999 do
  begin
    if isMultipleOf(i, 3) or isMultipleOf(i, 5) then
      sum := sum + i;
  end;
  writeln(sum);
end.


sum-divisible n:
	0
	for i range 1 -- n:
		if or = 0 % i 3 = 0 % i 5:
			+ i

!. sum-divisible 1000


function s( atom x )
	return 1 / power( x, 2 )
end function

function sum( atom low, atom high )
	atom ret = 0.0
	for i = low to high do
		ret = ret + s( i )
	end for
	return ret
end function

printf( 1, "%.15f\n", sum( 1, 1000 ) )


/* NetRexx */
options replace format comments java crossref symbols nobinary

parse arg input
inputs = ['1234', '01234', '0xfe', '0xf0e', '0', '00', '0,2' '1', '070', '77, 8' '0xf0e, 10', '070, 16', '0xf0e, 36', '000999ABCXYZ, 36', 'ff, 16', 'f, 10', 'z, 37'] -- test data
if input.length() > 0 then inputs = [input] -- replace test data with user input
loop i_ = 0 to inputs.length - 1
  in = inputs[i_]
  parse in val . ',' base .
  dSum = sumDigits(val, base)
  say 'Sum of digits for integer "'val'" for a given base of "'base'":' dSum'\-'
  -- Carry the exercise to it's logical conclusion and sum the results to give a single digit in range 0-9
  loop while dSum.length() > 1 & dSum.datatype('n')
    dSum = sumDigits(dSum, 10)
    say ',' dSum'\-'
    end
  say
  end i_

-- Sum digits of an integer
method sumDigits(val = Rexx, base = Rexx '') public static returns Rexx

  rVal = 0
  parse normalizeValue(val, base) val base .
  loop label digs for val.length()
    -- loop to extract digits from input and sum them
    parse val dv +1 val
    do
      rVal = rVal + Integer.valueOf(dv.toString(), base).intValue()
    catch ex = NumberFormatException
      rVal = 'NumberFormatException:' ex.getMessage()
      leave digs
    end
    end digs
  return rVal

-- Clean up the input, normalize the data and determine which base to use
method normalizeValue(inV = Rexx, base = Rexx '') private static returns Rexx
  inV = inV.strip('l')
  base = base.strip()
  parse inV xpref +2 . -
         =0 opref +1 . -
         =0 . '0x' xval . ',' . -
         =0 . '0'  oval . ',' . -
         =0 dval .

  select
    when xpref = '0x' & base.length() = 0 then do
      -- value starts with '0x' and no base supplied.  Assign hex as base
      inval = xval
      base = 16
      end
    when opref = '0'  & base.length() = 0 then do
      -- value starts with '0' and no base supplied.  Assign octal as base
      inval = oval
      base = 8
      end
    otherwise do
      inval = dval
      end
    end
  if base.length() = 0 then base = 10 -- base not set.  Assign decimal as base
  if inval.length() <= 0 then inval = 0 -- boundary condition.  Invalid input or a single zero
  rVal = inval base

  return rVal


(lib 'math) ;; divides?
(lib 'sequences) ;; sum/when

(define (task n  (k 3)  (p 5 ))
	 (when (!= (gcd k p) 1) (error "expected coprimes" (list k p)))
		(-
	 	(+ (sum/mults n k) (sum/mults n p)) ;; add multiples of k , multiples of p
	 	(sum/mults n (* k p)))) ;; remove multiples of k * p

;; using sequences
;; sum of multiples of k < n

(define (sum/mults n k)
	(sum/when (rcurry divides? k) [1 .. n]))

(task 1000 3 5)
    → 233168

;; using simple arithmetic - 🎩 young Gauss formula
;; sum of multiples of k < n  =
;; k*m*(m+1)/2 where m = floor(n/k)
(lib 'bigint)

(define (sum/mults n k)
	(set! n (quotient (1- n) k))
	(/ (* k n (1+ n )) 2))

(task 1e20 3 5)
    → 2333333333333333333316666666666666666668

(task 1000 42 666)
    ❌ error: expected coprimes (42 666)


sumOfSeries
=LAMBDA(f,
    LAMBDA(n,
        SUM(
            f(SEQUENCE(n, 1, 1, 1))
        )
    )
)

inverseSquare
=LAMBDA(n,
    1 / (n ^ 2)
)


## இந்த நிரல் தொடர் கூட்டல் (Sum Of Series) என்ற வகையைச் சேர்ந்தது

## இந்த நிரல் ஒன்று முதல் தரப்பட்ட எண் வரை 1/(எண் * எண்) எனக் கணக்கிட்டுக் கூட்டி விடை தரும்

நிரல்பாகம் தொடர்க்கூட்டல்(எண்1)

  எண்2 = 0

  @(எண்3 = 1, எண்3 <= எண்1, எண்3 = எண்3 + 1) ஆக

    ## ஒவ்வோர் எண்ணின் வர்க்கத்தைக் கணக்கிட்டு, ஒன்றை அதனால் வகுத்துக் கூட்டுகிறோம்

    எண்2 = எண்2 + (1 / (எண்3 * எண்3))

  முடி

  பின்கொடு (எண்2)

முடி

அ = int(உள்ளீடு("ஓர் எண்ணைச் சொல்லுங்கள்: "))

பதிப்பி "நீங்கள் தந்த எண் " அ
பதிப்பி "அதன் தொடர்க் கூட்டல் " தொடர்க்கூட்டல்(அ)


func sum_digits(n : int, base : int) -> int {
    var sum = 0;

    do
    {
        sum = sum + n % base;
        n = n / base
    }
    while (n != 0);

    sum
}

func main() -> int {
    print(sum_digits(1, 10));
    print(sum_digits(12345, 10));
    print(sum_digits(123045, 10));
    print(sum_digits(0xfe, 16));
    print(sum_digits(0Xf0e, 16));

    0
}


proc sumdigits(n, base: Natural): Natural =
  var n = n
  while n > 0:
    result += n mod base
    n = n div base

echo sumDigits(1, 10)
echo sumDigits(12345, 10)
echo sumDigits(123045, 10)
echo sumDigits(0xfe, 16)
echo sumDigits(0xf0e, 16)


MODULE SumDigits;
IMPORT Out;
PROCEDURE Sum(n: LONGINT;base: INTEGER): LONGINT;
VAR
	sum: LONGINT;
BEGIN
	sum := 0;
	WHILE (n > 0) DO
		INC(sum,(n MOD base));
		n := n DIV base
	END;
	RETURN sum
END Sum;
BEGIN
	Out.String("1     : ");Out.LongInt(Sum(1,10),10);Out.Ln;
	Out.String("1234  : ");Out.LongInt(Sum(1234,10),10);Out.Ln;
	Out.String("0FEH  : ");Out.LongInt(Sum(0FEH,16),10);Out.Ln;
	Out.String("OF0EH : ");Out.LongInt(Sum(0F0EH,16),10);Out.Ln
END SumDigits.


class
	APPLICATION

create
	make

feature {NONE}

	make
		do
			io.put_integer (sum_multiples (1000))
		end

	sum_multiples (n: INTEGER): INTEGER
			-- Sum of all positive multiples of 3 or 5 below 'n'.
		do
			across
				1 |..| (n - 1) as c
			loop
				if c.item \\ 3 = 0 or c.item \\ 5 = 0 then
					Result := Result + c.item
				end
			end
		end

end


let rec f (x : float) =
    match x with
        | 0. -> x
        | x -> (1. / (x * x)) + f (x - 1.)


class SumDigits {
  function : Main(args : String[]) ~ Nil {
    SumDigit(1)->PrintLine();
    SumDigit(12345)->PrintLine();
    SumDigit(0xfe, 16)->PrintLine();
    SumDigit(0xf0e, 16)->PrintLine();
  }

  function : SumDigit(value : Int, base : Int := 10) ~ Int {
    sum := 0;
    do {
      sum += value % base;
      value /= base;
    }
    while(value <> 0);
    return sum;
  }
}


let sum_digits ~digits ~base =
  let rec aux sum x =
    if x <= 0 then sum else
    aux (sum + x mod base) (x / base)
  in
  aux 0 digits

let () =
  Printf.printf "%d %d %d %d %d\n"
    (sum_digits 1 10)
    (sum_digits 12345 10)
    (sum_digits 123045 10)
    (sum_digits 0xfe 16)
    (sum_digits 0xf0e 16)


(defun sum-3-5 (n)
  (let ((sum 0))
    (dotimes (x n)
      (when (or (zerop (% x 3)) (zerop (% x 5)))
        (setq sum (+ sum x))))
    sum))


sum_3_5(X) when is_number(X) -> sum_3_5(erlang:round(X)-1, 0).
sum_3_5(X, Total) when X < 3 -> Total;
sum_3_5(X, Total) when X rem 3 =:= 0 orelse X rem 5 =:= 0 ->
  sum_3_5(X-1, Total+X);
sum_3_5(X, Total) ->
  sum_3_5(X-1, Total).

io:format("~B~n", [sum_3_5(1000)]).


: sum ( fn start count -- fsum )
  0e
  bounds do
    i s>d d>f dup execute f+
  loop drop ;

:noname ( x -- 1/x^2 ) fdup f* 1/f ;   ( xt )
1 1000 sum f.       \ 1.64393456668156
pi pi f* 6e f/ f.   \ 1.64493406684823


: sumDigits(n, base)  0 while( n ) [ n base /mod ->n + ] ;


(define (sum n base)
   (if (zero? n)
      n
      (+ (mod n base) (sum (div n base) base))))

(print (sum 1 10))
; ==> 1

(print (sum 1234 10))
; ==> 10

(print (sum #xfe 16))
; ==> 29

(print (sum #xf0e 16))
; ==> 29


dsum(n,base)=my(s); while(n, s += n%base; n \= base); s


let sum35 n = Seq.init n (id) |> Seq.reduce (fun sum i -> if i % 3 = 0 || i % 5 = 0 then sum + i else sum)

printfn "%d" (sum35 1000)
printfn "----------"

let sumUpTo (n : bigint) = n * (n + 1I) / 2I

let sumMultsBelow k n = k * (sumUpTo ((n-1I)/k))

let sum35fast n = (sumMultsBelow 3I n) + (sumMultsBelow 5I n) - (sumMultsBelow 15I n)

[for i = 0 to 30 do yield i]
|> List.iter (fun i -> printfn "%A" (sum35fast (bigint.Pow(10I, i))))


USING: kernel math prettyprint ;

: sum-multiples ( m n upto -- sum )
    >integer 1 - [ 2dup * ] dip
    [ 2dup swap [ mod - + ] [ /i * 2/ ] 2bi ] curry [email protected]
    [ + ] [ - ] bi* ;

3 5 1000 sum-multiples .
3 5 1e20 sum-multiples .


real, dimension(1000) :: a = (/ (1.0/(i*i), i=1, 1000) /)
real :: result

result = sum(a);


' FB 1.05.0 Win64

Const pi As Double = 3.141592653589793

Function sumSeries (n As UInteger) As Double
  If n = 0 Then Return 0
  Dim sum As Double = 0
  For k As Integer = 1 To n
    sum += 1.0/(k * k)
  Next
  Return sum
End Function

Print "s(1000) = "; sumSeries(1000)
Print "zeta(2) = "; Pi * pi / 6
Print
Print "Press any key to quit"
Sleep


Program SumOFDigits;

function SumOfDigitBase(n:UInt64;base:LongWord): LongWord;
var
  tmp: Uint64;
  digit,sum : LongWord;
Begin
  digit := 0;
  sum   := 0;
  While n > 0 do
  Begin
    tmp := n div base;
    digit := n-base*tmp;
    n := tmp;
    inc(sum,digit);
  end;
  SumOfDigitBase := sum;
end;
Begin
  writeln('   1 sums to ', SumOfDigitBase(1,10));
  writeln('1234 sums to ', SumOfDigitBase(1234,10));
  writeln(' $FE sums to ', SumOfDigitBase($FE,16));
  writeln('$FOE sums to ', SumOfDigitBase($F0E,16));

  writeln('18446744073709551615 sums to ', SumOfDigitBase(High(Uint64),10));

end.


#!/usr/bin/perl
use strict;
use warnings;

my %letval = map { $_ => $_ } 0 .. 9;
$letval{$_} = ord($_) - ord('a') + 10 for 'a' .. 'z';
$letval{$_} = ord($_) - ord('A') + 10 for 'A' .. 'Z';

sub sumdigits {
  my $number = shift;
  my $sum = 0;
  $sum += $letval{$_} for (split //, $number);
  $sum;
}

print "$_ sums to " . sumdigits($_) . "\n"
  for (qw/1 1234 1020304 fe f0e DEADBEEF/);


#APPTYPE CONSOLE

FUNCTION sumOfThreeFiveMultiples(n AS INTEGER)
    DIM sum AS INTEGER
    FOR DIM i = 1 TO n - 1
        IF (NOT (i MOD 3)) OR (NOT (i MOD 5)) THEN
            INCR(sum, i)
        END IF
    NEXT
    RETURN sum
END FUNCTION

PRINT sumOfThreeFiveMultiples(1000)
PAUSE


: main ( n -- )
  0 swap
  3 do
    i 3 mod 0= if
      i +
    else i 5 mod 0= if
      i +
    then then
  loop
  . ;

1000 main    \ 233168  ok


# We will compute the sum exactly

# Computing an approximation of a rationnal (giving a string)
# Value is truncated toward zero
Approx := function(x, d)
	local neg, a, b, n, m, s;
	if x < 0 then
		x := -x;
		neg := true;
	else
		neg := false;
	fi;
	a := NumeratorRat(x);
	b := DenominatorRat(x);
	n := QuoInt(a, b);
	a := RemInt(a, b);
	m := 10^d;
	s := "";
	if neg then
		Append(s, "-");
	fi;
	Append(s, String(n));
	n := Size(s) + 1;
	Append(s, String(m + QuoInt(a*m, b)));
	s[n] := '.';
	return s;
end;

a := Sum([1 .. 1000], n -> 1/n^2);;
Approx(a, 10);
"1.6439345666"
# and pi^2/6 is 1.6449340668, truncated to ten digits


function sum_digits(integer n, integer base)
integer res = 0
    while n do
        res += remainder(n,base)
        n = floor(n/base)
    end while
    return res
end function

?sum_digits(1,10)
?sum_digits(1234,10)
?sum_digits(#FE,16)
?sum_digits(#F0E,16)


<?php
function sumDigits($num, $base = 10) {
    $s = base_convert($num, 10, $base);
    foreach (str_split($s) as $c)
        $result += intval($c, $base);
    return $result;
}
echo sumDigits(1), "\n";
echo sumDigits(12345), "\n";
echo sumDigits(123045), "\n";
echo sumDigits(0xfe, 16), "\n";
echo sumDigits(0xf0e, 16), "\n";
?>


      INTEGER*8 FUNCTION SUMI(N)	!Sums the integers 1 to N inclusive.
Calculates as per the young Gauss: N*(N + 1)/2 = 1 + 2 + 3 + ... + N.
       INTEGER*8 N	!The number. Possibly large.
        IF (MOD(N,2).EQ.0) THEN	!So, I'm worried about overflow with N*(N + 1)
          SUMI = N/2*(N + 1)		!But since N is even, N/2 is good.
         ELSE			!Otherwise, if N is odd,
          SUMI = (N + 1)/2*N		!(N + 1) must be even.
        END IF			!Either way, the /2 reduces the result.
      END FUNCTION SUMI		!So overflow of intermediate results is avoided.

      INTEGER*8 FUNCTION SUMF(N,F)	!Sum of numbers up to N divisible by F.
       INTEGER*8 N,F		!The selection.
       INTEGER*8 L		!The last in range. N itself is excluded.
       INTEGER*8 SUMI		!Known type of the function.
        L = (N - 1)/F		!Truncates fractional parts.
        SUMF = F*SUMI(L)	!3 + 6 + 9 + ... = 3(1 + 2 + 3 + ...)
      END FUNCTION SUMF		!Could just put SUMF = F*SUMI((N - 1)/F).

      INTEGER*8 FUNCTION SUMBFI(N)	!Brute force and ignorance summation.
       INTEGER*8 N	!The number.
       INTEGER*8 I,S	!Stepper and counter.
        S = 0		!So, here we go.
        DO I = 3,N - 1	!N itself is not a candidate.
          IF (MOD(I,3).EQ.0 .OR. MOD(I,5).EQ.0) S = S + I	!Whee!
        END DO		!On to the next.
        SUMBFI = S		!The result.
      END FUNCTION SUMBFI	!Oh well, computers are fast these days.

      INTEGER*8 SUMF,SUMBFI	!Known type of the function.
      INTEGER*8 N	!The number.
      WRITE (6,*) "Sum multiples of 3 and 5 up to N"
   10 WRITE (6,11)		!Ask nicely.
   11 FORMAT ("Specify N: ",$)	!Obviously, the $ says 'stay on this line'.
      READ (5,*) N		!If blank input is given, further input will be requested.
      IF (N.LE.0) STOP		!Good enough.
      WRITE (6,*) "By Gauss:",SUMF(N,3) + SUMF(N,5) - SUMF(N,15)
      WRITE (6,*) "BFI sum :",SUMBFI(N)		!This could be a bit slow.
      GO TO 10			!Have another go.
      END	!So much for that.


[indent=4]
/*
   Sum of series, in Genie
   valac sumOfSeries.gs
   ./sumOfSeries
*/

delegate sumFunc(n:int):double

def sum_series(start:int, end:int, f:sumFunc):double
    sum:double = 0.0
    for var i = start to end do sum += f(i)
    return sum

def oneOverSquare(n:int):double
    return (1 / (double)(n * n))

init
    Intl.setlocale()
    print "ζ(2) approximation: %16.15f", sum_series(1, 1000, oneOverSquare)
    print "π² / 6            : %16.15f", Math.PI * Math.PI / 6.0


go =>

  println(1=sum_digits(1)),
  println(1234=sum_digits(1234)),

  println('"1234"'=sum_digits("1234")),
  println(1234=sum_digits(1234)),

  println('"fe(16)"'=sum_digits("fe", 16)), % -> 29
  println('"f0e(16)"'=sum_digits("f0e", 16)), % -> 29
  println('"FOE(16)"'=sum_digits("F0E", 16)), % -> 29
  println('123(16)'=sum_digits(123, 16)), % -> 6
  println('"123"(16)'=sum_digits("123", 16)), % -> 6

  println('"1110010101"(2)'=sum_digits("1110010101", 2)),

  println('"picat"(36)'=sum_digits("picat", 36)),

  Alpha = "0123456789abcdefghijklmnopqrstuvwxyz",
  Rand = [Alpha[1+random2() mod Alpha.length] : _ in 1..40],
  println(rand=Rand),
  println(rand_sum_digits=sum_digits(Rand, 36)),

  println("\nTesting exceptions"),
  catch(println(sum_digits(Rand, 10)), E, println(exception=E)), % bad_base
  catch(println(sum_digits("picat_is_fun!", 36)), E2, println(exeption=E2)), % bad_digit
  catch(println(sum_digits("11100101", 1)),E3,println(exception=E3)), % bad base
  catch(println(sum_digits("hi", 100)), E4, println(exception=E4)), % bad base

  % Output base
  println("\nOutput base"),
  println('"fe(16,10)"'=sum_digits("fe", 16,10)), % -> 29
  println('"fe(16,16)"'=sum_digits("fe", 16,16)), % -> 1d
  println('"f0e(16,16)"'=sum_digits("f0e", 16,16)), % -> 1d
  println('"1110010101"(2,2)'=sum_digits("1110010101", 2,2)), % -> 110
  println('"rosetta(36,36)"'=sum_digits("rosetta", 36,36)), % 4h
  nl.

% base 10
sum_digits(N) = sum([D.to_integer() : D in N.to_string()]), integer(N) => true.
sum_digits(N) = sum([D.to_integer() : D in N]), string(N) => true.

% base Base
sum_digits(N,Base) = sum_digits(N.to_string(), Base), integer(N) => true.
sum_digits(N,Base) = sum_digits(N,Base,10), string(N) => true.
sum_digits(N,Base,OutputBase) = Sum, string(N) =>
  N := to_lowercase(N),
  Alpha = "0123456789abcdefghijklmnopqrstuvwxyz",
  Map = new_map([A=I : {A,I} in zip(Alpha,0..length(Alpha)-1)]),
  M = [Map.get(I,-1) : I in N],
  if max(M) >= Base ; Base < 2; Base > Alpha.length then
    throw $bad_base('N'=N,base=Base)
  elseif min(M) == -1 then
    throw $bad_digits('N'=N,bad=[D : D in N, not Map.has_key(D) ])
  else
    if OutputBase != 10 then
      Sum = dec_to_base(sum(M),OutputBase)
    else
      Sum = sum(M)
    end
  end.

dec_to_base(N, Base) = [Alpha[D+1] : D in reverse(Res)] =>
  Alpha = "0123456789abcdefghijklmnopqrstuvwxyz",
  Res = [],
  while (N > 0)
    R := N mod Base,
    N := N div Base,
    Res := Res ++ [R]
  end.

base_to_dec(N, Base) = base_to_dec(N.to_string(), Base), integer(N) => true.
base_to_dec(N, Base) = Res =>
  println($base_to_dec(N, Base)),
  Alpha = "0123456789abcdefghijklmnopqrstuvwxyz",
  Map = new_map([A=I : {A,I} in zip(Alpha,0..length(Alpha)-1)]),
  Len = N.length,
  Res = sum([Map.get(D)*Base**(Len-I) : {D,I} in zip(N,1..N.length)]).


(de sumDigits (N Base)
   (or
      (=0 N)
      (+ (% N Base) (sumDigits (/ N Base) Base)) ) )


sum_digits: procedure options (main);   /* 4/9/2012 */
   declare ch character (1);
   declare (k, sd) fixed;

   on endfile (sysin) begin; put skip data (sd); stop; end;
   sd = 0;
   do forever;
      get edit (ch) (a(1)); put edit (ch) (a);
      k = index('abcdef', ch);
      if k > 0 then /* we have a base above 10 */
         sd = sd + 9 + k;
      else
         sd = sd + ch;
   end;
end sum_digits;


function Get-DigitalSum ([string] $number, $base = 10)
{
    if ($number.ToCharArray().Length -le 1) { [Convert]::ToInt32($number, $base) }
    else
    {
        $result = 0
        foreach ($character in $number.ToCharArray())
        {
            $digit = [Convert]::ToInt32(([string]$character), $base)
            $result += $digit
        }
        return $result
    }
}


' FB 1.05.0 Win64

Function sum35 (n As UInteger) As UInteger
  If n = 0 Then Return 0
  Dim As UInteger i, sum = 0
  For i = 1 To n
    If (i Mod 3 = 0) OrElse (i Mod 5 = 0) Then sum += i
  Next
  Return sum
End Function

Print "Sum of positive integers below 1000 divisible by 3 or 5 is : "; sum35(999)
Print
Print "Press any key to quit"
Sleep


sum999 = sum[select[1 to 999, {|n| n mod 3 == 0 or n mod 5 == 0}]]

sumdiv[n, d] :=
{
    m = floor[n/d]
    m(m + 1)/2 d
}

sum35big[n] := sumdiv[n, 3] + sumdiv[n, 5] - sumdiv[n, 15]

println["The sum of all the multiples of 3 or 5 below 1000 is $sum999"]
println["The sum of all multiples less than 1e20 is " + sum35big[1_00000_00000_00000_00000 - 1]]


package main

import ("fmt"; "math")

func main() {
    fmt.Println("known:   ", math.Pi*math.Pi/6)
    sum := 0.
    for i := 1e3; i > 0; i-- {
        sum += 1 / (i * i)
    }
    fmt.Println("computed:", sum)
}


digit_sum(N, Base, Sum):-
    digit_sum(N, Base, Sum, 0).

digit_sum(N, Base, Sum, S1):-
    N < Base,
    !,
    Sum is S1 + N.
digit_sum(N, Base, Sum, S1):-
    divmod(N, Base, M, Digit),
    S2 is S1 + Digit,
    digit_sum(M, Base, Sum, S2).

test_digit_sum(N, Base):-
    digit_sum(N, Base, Sum),
    writef('Sum of digits of %w in base %w is %w.\n', [N, Base, Sum]).

main:-
    test_digit_sum(1, 10),
    test_digit_sum(1234, 10),
    test_digit_sum(0xfe, 16),
    test_digit_sum(0xf0e, 16).


EnableExplicit

Procedure.i SumDigits(Number.q, Base)
  If Number < 0 : Number = -Number : EndIf; convert negative numbers to positive
  If Base < 2 : Base = 2 : EndIf ; base can't be less than 2
  Protected sum = 0
  While Number > 0
    sum + Number % Base
    Number / Base
  Wend
  ProcedureReturn sum
EndProcedure

If OpenConsole()
  PrintN("The sums of the digits are:")
  PrintN("")
  PrintN("1    base 10 : " + SumDigits(1, 10))
  PrintN("1234 base 10 : " + SumDigits(1234, 10))
  PrintN("fe   base 16 : " + SumDigits($fe, 16))
  PrintN("f0e  base 16 : " + SumDigits($f0e, 16))
  PrintN("")
  PrintN("Press any key to close the console")
  Repeat: Delay(10) : Until Inkey() <> ""
  CloseConsole()
EndIf


package main

import "fmt"

func main() {
    fmt.Println(s35(1000))
}

func s35(n int) int {
    n--
    threes := n / 3
    fives := n / 5
    fifteen := n / 15

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

    n = (threes + fives - fifteen) / 2

    return n
}


def sumMul = { n, f -> BigInteger n1 = (n - 1) / f; f * n1 * (n1 + 1) / 2 }
def sum35 = { sumMul(it, 3) + sumMul(it, 5) - sumMul(it, 15) }


using StringTools;

class Main {
  static function main() {
    var sum = 0.0;
    for (x in 1...1001)
      sum += 1.0/(x * x);
    Sys.println('Approximation: $sum');
    Sys.println('Exact: '.lpad(' ', 15) + Math.PI * Math.PI / 6);
  }
}


REAL :: a(1000)
        a = 1 / $^2
        WRITE(ClipBoard, Format='F17.15') SUM(a)


from numpy import base_repr

def sumDigits(num, base=10):
    return sum(int(x, base) for x in list(base_repr(num, base)))


  [ temp put 0
    [ over while
      swap temp share /mod
      rot + again ]
    nip temp release ]     is digitsum ( n n --> n )

        1 10 digitsum echo sp
     1234 10 digitsum echo sp
   hex FE 16 digitsum echo sp
  hex F0E 16 digitsum echo


change.base <- function(n, base)
{
  ret <- integer(as.integer(logb(x=n, base=base))+1L)

  for (i in 1:length(ret))
  {
    ret[i] <- n %% base
    n <- n %/% base

  }

  return(ret)
}

sum.digits <- function(n, base=10)
{
  if (base < 2)
    stop("base must be at least 2")

  return(sum(change.base(n=n, base=base)))
}

sum.digits(1)
sum.digits(12345)
sum.digits(123045)
sum.digits(0xfe, 16)
sum.digits(0xf0e, 16)


import Data.List (nub)

----------------- SUM MULTIPLES OF 3 AND 5 ---------------

sum35 :: Integer -> Integer
sum35 n = f 3 + f 5 - f 15
  where
    f = sumMul n

sumMul :: Integer -> Integer -> Integer
sumMul n f = f * n1 * (n1 + 1) `div` 2
  where
    n1 = (n - 1) `div` f

--------------------------- TEST -------------------------
main :: IO ()
main =
  mapM_
    print
    [ sum35 1000,
      sum35 100000000000000000000000000000000,
      sumMulS 1000 [3, 5],
      sumMulS 10000000 [2, 3, 5, 7, 11, 13]
    ]

---------------- FOR VARIABLE LENGTH INPUTS --------------

pairLCM :: [Integer] -> [Integer]
pairLCM [] = []
pairLCM (x : xs) = (lcm x <$> xs) <> pairLCM xs

sumMulS :: Integer -> [Integer] -> Integer
sumMulS _ [] = 0
sumMulS n s =
  ( ((-) . sum . fmap f)
      <*> (g . pairLCM)
  )
    (nub s)
  where
    f = sumMul n
    g = sumMulS n


procedure main()
   local i, sum
   sum := 0 & i := 0
   every sum +:= 1.0/((| i +:= 1 ) ^ 2) \1000
   write(sum)
end


#lang racket
(define (sum-of-digits n base (sum 0))
  (if (= n 0)
      sum
      (sum-of-digits (quotient n base)
                     base
                     (+ (remainder n base) sum))))

(for-each
 (lambda (number-base-pair)
   (define number (car number-base-pair))
   (define base (cadr number-base-pair))
   (displayln (format "(~a)_~a = ~a" number base (sum-of-digits number base))))
 '((1 10) (1234 10) (#xfe 16) (#xf0e 16)))

;  outputs:
;    (1)_10 = 1
;    (1234)_10 = 10
;    (254)_16 = 29
;    (3854)_16 = 29


/* REXX **************************************************************
* 04.12.2012 Walter Pachl
**********************************************************************/
digits='0123456789ABCDEF'
Do i=1 To length(digits)
  d=substr(digits,i,1)
  value.d=i-1
  End
Call test '1'
Call test '1234'
Call test 'FE'
Call test 'F0E'
Exit
test:
  Parse Arg number
  res=right(number,4)
  dsum=0
  Do While number<>''
    Parse Var number d +1 number
    dsum=dsum+value.d
    End
  Say res '->' right(dsum,2)
  Return


procedure main(A)
    n := (integer(A[1]) | 1000)-1
    write(sum(n,3)+sum(n,5)-sum(n,15))
end

procedure sum(n,m)
    return m*((n/m)*(n/m+1)/2)
end


NB. Naive method
NB. joins two lists of the multiples of 3 and 5, then uses the ~. operator to remove duplicates.

echo 'The sum of the multiples of 3 or 5 < 1000 is ', ": +/ ~. (3*i.334), (5*i.200)

NB. inclusion/exclusion

triangular =: -:@:(*: + 1&*)
sumdiv =: dyad define
    (triangular <. x % y) * y
)

echo 'For 10^20 - 1, the sum is ', ": +/ (".(20#'9'),'x') sumdiv 3 5 _15
exit ''


   NB. sum of reciprocals of squares of first thousand positive integers
   +/ % *: >: i. 1000
1.64393

   (*:o.1)%6       NB. pi squared over six, for comparison
1.64493

   1r6p2           NB.  As a constant (J has a rich constant notation)
1.64493


public class Sum{
    public static double f(double x){
       return 1/(x*x);
    }

    public static void main(String[] args){
       double start = 1;
       double end = 1000;
       double sum = 0;

       for(double x = start;x <= end;x++) sum += f(x);

       System.out.println("Sum of f(x) from " + start + " to " + end +" is " + sum);
    }
}


see "sum digits of 1 = " + sumDigits(1) + nl
see "sum digits of 1234 = " + sumDigits(1234) + nl

func sumDigits n
     sum = 0
     while n > 0.5
           m = floor(n / 10)
           digit = n - m * 10
           sum = sum + digit
           n = m
     end
     return sum


def sum_digits(num, base = 10) = num.digits(base).sum


struct DigitIter(usize, usize);

impl Iterator for DigitIter {
    type Item = usize;
    fn next(&mut self) -> Option<Self::Item> {
        if self.0 == 0 {
            None
        } else {
            let ret = self.0 % self.1;
            self.0 /= self.1;
            Some(ret)
        }
    }
}

fn main() {
    println!("{}", DigitIter(1234,10).sum::<usize>());
}


class SumMultiples {
	public static long getSum(long n) {
		long sum = 0;
		for (int i = 3; i < n; i++) {
			if (i % 3 == 0 || i % 5 == 0) sum += i;
		}
		return sum;
	}
	public static void main(String[] args) {
		System.out.println(getSum(1000));
	}
}


#!/usr/bin/jsish
/* Sum of a series */
function sum(a:number, b:number , fn:function):number {
   var s = 0;
   for ( ; a <= b; a++) s += fn(a);
   return s;
}

;sum(1, 1000, function(x) { return 1/(x*x); } );

/*
=!EXPECTSTART!=
sum(1, 1000, function(x) { return 1/(x*x); } ) ==> 1.643934566681561
=!EXPECTEND!=
*/


def sumDigits(x:BigInt, base:Int=10):BigInt=sumDigits(x.toString(base), base)
def sumDigits(x:String, base:Int):BigInt = x map(_.asDigit) sum


(import (scheme base)
        (scheme write))

;; convert number to a list of digits, in desired base
(define (number->list n base)
  (let loop ((res '())
             (num n))
    (if (< num base)
      (cons num res)
      (loop (cons (remainder num base) res)
            (quotient num base)))))

;; return the sum of digits of n in given base
(define (sum-digits n base)
  (apply + (number->list n base)))

;; test cases:
;; -- this displays each number in its original, given-base, for comparison
;; -- target-base is the base in which to consider each number represented, for summing the digits
(define (test-case n given-base target-base)
  (display (string-append (number->string n given-base)
                          " base "
                          (number->string given-base)
                          " has decimal value "
                          (number->string n)
                          " => sum of digits in base "
                          (number->string target-base)
                          " is "
                          (number->string (sum-digits n target-base))))
  (newline))

(test-case 1 10 10)
(test-case 1234 10 10)
(test-case #o1234 8 10)
(test-case #xFE 16 16)
(test-case #xFE 16 10)
(test-case #xF0E 16 16)
(test-case #b1101010101010101010101010101010101 2 2)
(test-case #b1101010101010101010101010101010101 2 10)
(test-case #b1101010101010101010101010101010101 2 1000)


def sum_multiples(d):
 ((./d) | floor) |  (d * . * (.+1))/2 ;

# Sum of multiples of a or b that are less than . (the input)
def task(a;b):
 . - 1
 | sum_multiples(a) + sum_multiples(b) - sum_multiples(a*b);


multsum(n, m, lim) = sum(0:n:lim-1) + sum(0:m:lim-1) - sum(0:lcm(n,m):lim-1)


// version 1.1.2

import java.math.BigInteger

val big2  = BigInteger.valueOf(2)
val big3  = BigInteger.valueOf(3)
val big5  = BigInteger.valueOf(5)
val big15 = big3 * big5

fun sum35(n: Int) = (3 until n).filter { it % 3 == 0 || it % 5 == 0}.sum()

fun sum35(n: BigInteger): BigInteger {
    val nn    = n - BigInteger.ONE
    val num3  = nn / big3
    val end3  = num3 * big3
    val sum3  = (big3 + end3) * num3 / big2
    val num5  = nn / big5
    val end5  = num5 * big5
    val sum5  = (big5 + end5) * num5 / big2
    val num15 = nn / big15
    val end15 = num15 * big15
    val sum15 = (big15 + end15) * num15 / big2
    return sum3 + sum5 - sum15
}

fun main(args: Array<String>) {
    println("The sum of multiples of 3 or 5 below 1000 is ${sum35(1000)}")
    val big100k = BigInteger.valueOf(100_000L)
    val e20 = big100k * big100k * big100k * big100k
    println("The sum of multiples of 3 or 5 below 1e20 is ${sum35(e20)}")
}


// version 1.0.6

fun main(args: Array<String>) {
    val n = 1000
    val sum = (1..n).sumByDouble { 1.0 / (it * it) }
    println("Actual sum is $sum")
    println("zeta(2)    is ${Math.PI * Math.PI / 6.0}")
}


$ include "seed7_05.s7i";

const func integer: sumDigits (in var integer: num, in integer: base) is func
  result
     var integer: sum is 0;
  begin
    while num > 0 do
      sum +:= num rem base;
      num := num div base;
    end while;
  end func;

const proc: main is func
  begin
    writeln(sumDigits(1,      10));
    writeln(sumDigits(12345,  10));
    writeln(sumDigits(123045, 10));
    writeln(sumDigits(123045, 50));
    writeln(sumDigits(16#fe,  10));
    writeln(sumDigits(16#fe,  16));
    writeln(sumDigits(16#f0e, 16));
  end func;


func Σ(String str, base=36) {
    str.chars.map{ Num(_, base) }.sum
}

<1 1234 1020304 fe f0e DEADBEEF>.each { |n|
    say "Σ(#{n}) = #{Σ(n)}"
}


/*
This code is an implementation of "Sum digits of an integer" in SQL ORACLE 19c
p_in_str -- input string
*/
WITH
  FUNCTION sum_digits(p_in_str IN varchar2) RETURN varchar2 IS
  v_in_str VARCHAR(32767) := translate(p_in_str,'*-+','*');
  v_sum INTEGER;
BEGIN
  --
  IF regexp_count(v_in_str,'[0-9A-F]',1,'i')=LENGTH(v_in_str) THEN -- base 16
    EXECUTE immediate 'select sum('||regexp_replace(v_in_str,'(\w)','to_number(''\1'',''X'')+')||'0) from dual' INTO v_sum;
    --
  elsif regexp_count(v_in_str,'[0-9]',1,'i')=LENGTH(v_in_str) THEN -- base 10
    EXECUTE immediate 'select sum('||regexp_replace(v_in_str,'(\d)','\1+')||'0) from dual' INTO v_sum;
    --
  ELSE
    RETURN 'Sum of digits for integer "'||p_in_str||'" not defined';
    --
  END IF;
  --
  RETURN 'Sum of digits for integer "'||p_in_str||'" = '||v_sum;
END;

--Test
SELECT sum_digits('') AS res FROM dual
UNION ALL
SELECT sum_digits('000') AS res FROM dual
UNION ALL
SELECT sum_digits('-010') AS res FROM dual
UNION ALL
SELECT sum_digits('+010') AS res FROM dual
UNION ALL
SELECT sum_digits('120034') AS res FROM dual
UNION ALL
SELECT sum_digits('FE') AS res FROM dual
UNION ALL
SELECT sum_digits('f0e') AS res FROM dual
UNION ALL
SELECT sum_digits('öst12') AS res FROM dual;


local(limit = 1)
while(#limit <= 100000) => {^
	local(s = 0)
	loop(-from=3,-to=#limit-1) => {
		not (loop_count % 3) || not (loop_count % 5) ? #s += loop_count
	}
	'The sum of multiples of 3 or 5 between 1 and '+(#limit-1)+' is: '+#s+'\r'
	#limit = integer(#limit->asString + '0')
^}


implement Sum3and5;

include "sys.m"; sys: Sys;
include "draw.m";
include "ipints.m"; ipints: IPints;
	IPint: import ipints;

Sum3and5: module {
	init: fn(nil: ref Draw->Context, args: list of string);
};

ints: array of ref IPint;

init(nil: ref Draw->Context, args: list of string)
{
	sys = load Sys Sys->PATH;
	ipints = load IPints IPints->PATH;

	# We use 1, 2, 3, 5, and 15:
	ints = array[16] of ref IPint;
	for(i := 0; i < len ints; i++)
		ints[i] = IPint.inttoip(i);

	args = tl args;
	while(args != nil) {
		h := hd args;
		args = tl args;
		# If it's big enough that the result might not
		# fit inside a big, we use the IPint version.
		if(len h > 9) {
			sys->print("%s\n", isum3to5(IPint.strtoip(h, 10)).iptostr(10));
		} else {
			sys->print("%bd\n", sum3to5(big h));
		}
	}
}

triangle(n: big): big
{
	return((n * (n + big 1)) / big 2);
}

sum_multiples(n: big, limit: big): big
{
	return(n * triangle((limit - big 1) / n));
}

sum3to5(limit: big): big
{
	return(
		sum_multiples(big 3, limit) +
		sum_multiples(big 5, limit) -
		sum_multiples(big 15, limit));
}

itriangle(n: ref IPint): ref IPint
{
	return n.mul(n.add(ints[1])).div(ints[2]).t0;
}

isum_multiples(n: ref IPint, limit: ref IPint): ref IPint
{
	return n.mul(itriangle(limit.sub(ints[1]).div(n).t0));
}

isum3to5(limit: ref IPint): ref IPint
{
	return(
		isum_multiples(ints[3], limit).
		add(isum_multiples(ints[5], limit)).
		sub(isum_multiples(ints[15], limit)));
}


define sum_of_a_series(n::integer,k::integer) => {
	local(sum = 0)
	loop(-from=#k,-to=#n) => {
		#sum += 1.00/(math_pow(loop_count,2))
	}
	return #sum
}
sum_of_a_series(1000,1)


fun sumDigits (0, _) = 0
  | sumDigits (n, base) = n mod base + sumDigits (n div base, base)

val testInput = [(1, 10), (1234, 10), (0xfe, 16), (0xf0e, 16)]
val () = print (String.concatWith " " (map (Int.toString o sumDigits) testInput) ^ "\n")


function sumdigits(s) {
	a = ascii(strupper(s)):-48
	return(sum(a:-(a:>9)*7))
}

sumdigits("1")
  1

sumdigits("1234")
  10

sumdigits("fe")
  29

sumdigits("f0e")
  29

sumdigits(inbase(16, 254, 10))
  29


extension String: Error {
    func sumDigits(withBase base: Int) throws -> Int {
        func characterToInt(_ base: Int) -> (Character) -> Int? {
            return { char in
                return Int(String(char), radix: base)
            }
        }

        return try self.map(characterToInt(base))
            .flatMap {
                guard $0 != nil else { throw "Invalid input" }
                return $0
            }
            .reduce(0, +)
    }
}

print(try! "1".sumDigits(withBase: 10))
print(try! "1234".sumDigits(withBase: 10))
print(try! "fe".sumDigits(withBase: 16))
print(try! "f0e".sumDigits(withBase: 16))


proc sumDigits {num {base 10}} {
    set total 0
    foreach d [split $num ""] {
	if {[string is alpha $d]} {
	    set d [expr {[scan [string tolower $d] %c] - 87}]
	} elseif {![string is digit $d]} {
	    error "bad digit: $d"
	}
	if {$d >= $base} {
	    error "bad digit: $d"
	}
	incr total $d
    }
    return $total
}


on sum35 (n)
  res = 0
  repeat with i = 0 to (n-1)
    if i mod 3=0 OR i mod 5=0 then
      res = res + i
    end if
  end repeat
  return res
end


function sumUntil n
    repeat with i = 0 to (n-1)
        if i mod 3 = 0 or i mod 5 = 0 then
            add i to m
        end if
    end repeat
    return m
end sumUntil

put sumUntil(1000)  // 233168


function tri (n) return n * (n + 1) / 2 end

function sum35 (n)
	n = n - 1
	return	(	3 * tri(math.floor(n / 3)) +
			5 * tri(math.floor(n / 5)) -
			15 * tri(math.floor(n / 15))
		)
end

print(sum35(1000))
print(sum35(1e+20))


(defun sum-series (nums)
  (lists:foldl
    #'+/2
    0
    (lists:map
      (lambda (x) (/ 1 x x))
      nums)))


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

print sum

end


"01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"→Str1
Disp "SUM DIGITS OF INT"
Disp "-----------------"
Disp "ENTER NUMBER"
Input Str2
Disp "ENTER BASE"
Input B
0→R
length(Str2)→L
For(I,1,L,1)
sub(Str2,I,1)→Str3
inString(Str1,Str3)-1→S
If S≥B or S=-1:Then
Disp "ERROR:"
Disp Str3
Disp "NOT IN BASE"
Disp B
Stop
End
R+S→R
End
Disp R


#lang transd

MainModule : {
    v10: [1, 1234, 10000000],
    vvar: ["fe:16", "f0e:16", "2022:3", "Transd:30"],

    sumDigits: (λ s String()
        (with snum (substr s 0 ":")
              base (first (substr s after: ":") "10") n 0
        (textout "sum of " :left width: 10 (+ snum ":" base " : " ))
        (tsd (split snum "") :reduce
            using: (λ s String() (+= n (to-Int (+ s ":" base))))) (lout n))
    ),

    _start: (lambda
        (tsd v10 reduce: ["(to-String col1)"]
                 using: (λ s String() (sumDigits s)))
        (tsd vvar reduce: ["(sumDigits col1)"] )
    )
}


// Sum digits of an integer

function sumOfDigitBase(n: number, bas: number): number {
  var digit = 0, sum = 0;
  while (n > 0)
  {
    var tmp = Math.floor(n / bas);
    digit = n - bas * tmp;
    n = tmp;
    sum += digit;
  }
  return sum;
}

console.log(`    1 sums to ${sumOfDigitBase(1, 10)}`);
console.log(` 1234 sums to ${sumOfDigitBase(1234, 10)}`);
console.log(` 0xfe sums to ${sumOfDigitBase(0xfe, 16)}`);
console.log(`0xf0e sums to ${sumOfDigitBase(0xf0e, 16)}`);
maxint = Number.MAX_SAFE_INTEGER;
console.log(`${maxint} (Number.MAX_SAFE_INTEGER) sums to ${sumOfDigitBase(maxint, 10)}`);


the floatprecision = 8
sum = 0
repeat with i = 1 to 1000
  sum = sum + 1/power(i, 2)
end repeat
put sum
-- 1.64393457


repeat with i = 1 to 1000
    add 1/(i^2) to summ
end repeat
put summ  //1.643935


to series :fn :a :b
  localmake "sigma 0
  for [i :a :b] [make "sigma :sigma + invoke :fn :i]
  output :sigma
end
to zeta.2 :x
  output 1 / (:x * :x)
end
print series "zeta.2 1 1000
make "pi (radarctan 0 1) * 2
print :pi * :pi / 6


def sumDigits (string val, int base)
	decl int ret
	for (decl int i) (< i (size val)) (inc i)
		set ret (+ ret (int val<i> base))
	end for
	return ret
end sumDigits


Function sumDigits(num As Variant, base As Long) As Long
    'can handle up to base 36
    Dim outp As Long
    Dim validNums As String, tmp As Variant, x As Long, lennum As Long
    'ensure num contains only valid characters
    validNums = Left$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", base)
    lennum = Len(num)
    For L0 = lennum To 1 Step -1
        x = InStr(validNums, Mid$(num, L0, 1)) - 1
        If -1 = x Then Exit Function
        tmp = tmp + (x * (base ^ (lennum - L0)))
    Next
    While tmp
        outp = outp + (tmp Mod base)
        tmp = tmp \ base
    Wend
    sumDigits = outp
End Function

Sub tester()
    Debug.Print sumDigits(1, 10)
    Debug.Print sumDigits(1234, 10)
    Debug.Print sumDigits(&HFE, 16)
    Debug.Print sumDigits(&HF0E, 16)
    Debug.Print sumDigits("2", 2)
End Sub


import "/fmt" for Fmt, Conv

var sumDigits = Fn.new { |n, b|
    var sum = 0
    while (n > 0) {
        sum = sum + n%b
        n = (n/b).truncate
    }
    return sum
}

var tests = [ [1, 10], [1234, 10], [0xfe, 16], [0xf0e, 16], [1411, 8], [111, 3] ]
System.print("The sum of the digits is:")
for (test in tests) {
    var n = test[0]
    var b = test[1]
    var sum = sumDigits.call(n, b)
    System.print("%(Fmt.s(-5, Conv.itoa(n, b))) in base %(Fmt.d(2, b)) = %(Fmt.d(2, sum))")
}


sumi(n, inc):= block(
  [kmax],

  /* below n means [1 .. n-1] */
  kmax: quotient(n-1, inc),
  return(
    ''(ev(sum(inc*k, k, 1, kmax), simpsum))
  )
);

sum35(n):= sumi(n, 3) + sumi(n, 5) - sumi(n, 15);

sum35(1000);
sum35(10^20);


// simple version:
sum35 = function(n)
    sum = 0
    for i in range(3, n-1, 3)
        sum = sum + i
    end for
    for i in range(5, n-1, 5)
        if i % 3 then sum = sum + i // (skip multiples of 3 here)
    end for
    return sum
end function

print sum35(1000)


sum = 0
for i = 1, 1000 do sum = sum + 1/i^2 end
print(sum)


series = ssum asa  n >= 1000
   where
         num = 1 fby num + 1;
         ssum = ssum + 1/(num * num)
   end;


code    ChOut=8, CrLf=9, IntOut=11;

func    SumDigits(N, Base);
int     N, Base, Sum;
[Sum:= 0;
repeat  N:= N/Base;
        Sum:= Sum + rem(0);
until   N=0;
return Sum;
];

[IntOut(0, SumDigits(1,      10));  ChOut(0, ^ );
 IntOut(0, SumDigits(12345,  10));  ChOut(0, ^ );
 IntOut(0, SumDigits(123045, 10));  ChOut(0, ^ );
 IntOut(0, SumDigits($FE,    10));  ChOut(0, ^ );
 IntOut(0, SumDigits($FE,    16));  ChOut(0, ^ );
 IntOut(0, SumDigits($F0E,   16));  CrLf(0);
]


fcn sum(n,b=10){
   if(b==10) n.split().sum(0);  // digits to list
   else      n.toString(b).split("").apply("toInt",b).sum(0);
}


def getSum(n)
        sum = 0
        for i in range(3, n - 1)
                if (i % 3 = 0) or (i % 5 = 0)
                        sum += i
                end
        end
        return sum
end

println getSum(1000)


/* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 40

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method summing(maxLimit = 1000) public static
  mult = 0
  loop mv = 0 while mv < maxLimit
    if mv // 3 = 0 | mv // 5 = 0 then
      mult = mult + mv
    end mv
  return mult

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- translation of Raku
method sum_mults(first, limit) public static
  last = limit - 1
  last = last - last // first
  sum = (last / first) * (first + last) % 2
  return sum

method sum35(maxLimit) public static
  return sum_mults(3, maxLimit) + sum_mults(5, maxLimit) - sum_mults(15, maxLimit)

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static

  offset = 30
  incr = 10

  say 'Limit'.right(offset) || '|' || 'Sum'
  say '-'.copies(offset)    || '+' || '-'.copies(60)
  timing = System.nanoTime
  sum = summing()
  timing = System.nanoTime - timing
  say 1000.format.right(offset)'|'sum
  say 'Elapsed time:' Rexx(timing * 1e-9).format(4, 6)'s'
  say

  say 'Limit'.right(offset) || '|' || 'Sum'
  say '-'.copies(offset)    || '+' || '-'.copies(60)
  tmax = 1e+6
  timing = System.nanoTime
  mm = 1
  loop while mm <= tmax
    say mm.right(offset)'|'summing(mm)
    mm = mm * incr
    end
  timing = System.nanoTime - timing
  say 'Elapsed time:' Rexx(timing * 1e-9).format(4, 6)'s'
  say

  say 'Limit'.right(offset) || '|' || 'Sum'
  say '-'.copies(offset)    || '+' || '-'.copies(60)
  timing = System.nanoTime
  sum = sum35(1000)
  timing = System.nanoTime - timing
  say 1000.format.right(offset)'|'sum
  say 'Elapsed time:' Rexx(timing * 1e-9).format(4, 6)'s'
  say

  say 'Limit'.right(offset) || '|' || 'Sum'
  say '-'.copies(offset)    || '+' || '-'.copies(60)
  tmax = 1e+27
  timing = System.nanoTime
  mm = 1
  loop while mm <= tmax
    say mm.right(offset)'|'sum35(mm)
    mm = mm * incr
    end
  timing = System.nanoTime - timing
  say 'Elapsed time:' Rexx(timing * 1e-9).format(4, 6)'s'
  say
  return


proc sum35(n: int): int =
  for x in 0 ..< n:
    if x mod 3 == 0 or x mod 5 == 0:
      result += x

echo sum35(1000)


class SumMultiples {
  function : native : GetSum(n : Int) ~ Int {
    sum := 0;
    for(i := 3; i < n; i++;) {
      if(i % 3 = 0 | i % 5 = 0) {
        sum += i;
      };
    };

    return sum;
  }

  function : Main(args : String[]) ~ Nil {
    GetSum(1000)->PrintLine();
  }
}


total = 0
for i in 1 to 1000 do
(
    total += 1.0 / pow i 2
)
print total


0 1 (
  ((dup * 1 swap /) (id)) cleave
  ((+) (succ)) spread
) 1000 times pop print


zeta = function(num)
    return 1 / num^2
end function

sum = function(start, finish, formula)
    total = 0
    for i in range(start, finish)
        total = total + formula(i)
    end for
    return total
end function

print sum(1, 1000, @zeta)


let sum_mults n =
        let sum = ref 0 in
        for i = 3 to (n - 1) do
                if (i mod 3) = 0 || (i mod 5) = 0 then
                        sum := !sum + i;
        done;
        !sum;;

print_endline (string_of_int (sum_mults 1000));;


999 seq filter(#[ dup 3 mod 0 == swap 5 mod 0 == or ]) sum println


x	IS	$1	% flt calculations
y	IS	$2	%   id
z	IS	$3	% z = sum series
t	IS	$4	% temp var

	LOC	Data_Segment
	GREG	@
BUF	OCTA	0,0,0		% print buffer

	LOC	#1000
	GREG	@

// print floating point number in scientific format: 0.xxx...ey..
// most of this routine is adopted from:
// http://www.pspu.ru/personal/eremin/emmi/rom_subs/printreal.html
// float number in z
	GREG	@
NaN	BYTE	"NaN..",0
NewLn	BYTE	#a,0
1H	LDA	x,NaN
	TRAP	0,Fputs,StdOut
	GO	$127,$127,0

prtFlt	FUN	x,z,z		% test if z == NaN
	BNZ	x,1B
	CMP	$73,z,0		% if necessary remember it is neg
	BNN	$73,4F
Sign	BYTE	'-'
	LDA	$255,Sign
	TRAP	0,Fputs,StdOut
	ANDNH	z,#8000		% make number pos
// normalizing float number
4H	SETH	$74,#4024	% initialize mulfactor = 10.0
	SETH	$73,#0023
	INCMH	$73,#86f2
	INCML	$73,#6fc1	%
	FLOT	$73,$73		% $73 = float 10^16
	SET	$75,16		% set # decimals to 16
8H	FCMP	$72,z,$73	% while z >= 10^16 do
	BN	$72,9F		%
	FDIV	z,z,$74		%  z = z / 10.0
	ADD	$75,$75,1	%  incr exponent
	JMP	8B		% wend
9H	FDIV	$73,$73,$74	% 10^16 / 10.0
5H	FCMP	$72,z,$73	% while z < 10^15 do
	BNN	$72,6F
	FMUL	z,z,$74		%  z = z * 10.0
	SUB	$75,$75,1	%  exp = exp - 1
	JMP	5B
NulPnt	BYTE	'0','.',#00
6H	LDA	$255,NulPnt	% print '0.' to StdOut
	TRAP	0,Fputs,StdOut
	FIX	z,0,z		% convert float z to integer
// print mantissa
0H	GREG	#3030303030303030
	STO	0B,BUF
	STO	0B,BUF+8	% store print mask in buffer
	LDA	$255,BUF+16	% points after LSD
				% repeat
2H	SUB	$255,$255,1	%   move pointer down
	DIV	z,z,10		%   (q,r) = divmod z 10
	GET	t,rR		%   get remainder
	INCL	t,'0'		%   convert to ascii digit
	STBU	t,$255,0	%   store digit in buffer
	BNZ	z,2B		% until q == 0
	TRAP	0,Fputs,StdOut	% print mantissa
Exp	BYTE	'e',#00
	LDA	$255,Exp	% print 'exponent' indicator
	TRAP	0,Fputs,StdOut
// print exponent
0H	GREG	#3030300000000000
	STO	0B,BUF
	LDA	$255,BUF+2	% store print mask in buffer
	CMP	$73,$75,0	% if exp neg then place - in buffer
	BNN	$73,2F
ExpSign	BYTE	'-'
	LDA	$255,ExpSign
	TRAP	0,Fputs,StdOut
	NEG	$75,$75		% make exp positive
2H	LDA	$255,BUF+3	% points after LSD
				% repeat
3H	SUB	$255,$255,1	%   move pointer down
	DIV	$75,$75,10	%   (q,r) = divmod exp 10
	GET	t,rR
	INCL	t,'0'
	STBU	t,$255,0	%   store exp. digit in buffer
	BNZ	$75,3B		% until q == 0
	TRAP	0,Fputs,StdOut	% print exponent
	LDA	$255,NewLn
	TRAP	0,Fputs,StdOut	% do a NL
	GO	$127,$127,0	% return

i  IS $5 ;iu IS $6
Main	SET	iu,1000
	SETH	y,#3ff0     y = 1.0
	SETH	z,#0000     z = 0.0
	SET	i,1          for (i=1;i<=1000; i++ ) {
1H	FLOT	x,i           x = int i
	FMUL	x,x,x         x = x^2
	FDIV	x,y,x         x = 1 / x
	FADD	z,z,x         s = s + x
	ADD	i,i,1
	CMP	t,i,iu
	PBNP	t,1B         } z = sum
	GO	$127,prtFlt  print sum --> StdOut
	TRAP	0,Halt,0


(print
(fold (lambda (s x)
         (+ s (if (or (zero? (remainder x 3)) (zero? (remainder x 5))) x 0)))
   0 (iota 1000)))
; ==> 233168


MODULE SeriesSum;
FROM InOut IMPORT WriteLn;
FROM RealInOut IMPORT WriteReal;

TYPE RealFunc = PROCEDURE (REAL): REAL;

PROCEDURE seriesSum(k, n: CARDINAL; f: RealFunc): REAL;
    VAR total: REAL;
        i: CARDINAL;
BEGIN
    total := 0.0;
    FOR i := k TO n DO
        total := total + f(FLOAT(i));
    END;
    RETURN total;
END seriesSum;

PROCEDURE oneOverKSquared(k: REAL): REAL;
BEGIN
    RETURN 1.0 / (k * k);
END oneOverKSquared;

BEGIN
    WriteReal(seriesSum(1, 1000, oneOverKSquared), 10);
    WriteLn;
END SeriesSum.


MODULE Sum EXPORTS Main;

IMPORT IO, Fmt, Math;

VAR sum: LONGREAL := 0.0D0;

PROCEDURE F(x: LONGREAL): LONGREAL =
  BEGIN
    RETURN 1.0D0 / Math.pow(x, 2.0D0);
  END F;

BEGIN
  FOR i := 1 TO 1000 DO
    sum := sum + F(FLOAT(i, LONGREAL));
  END;
  IO.Put("Sum of F(x) from 1 to 1000 is ");
  IO.Put(Fmt.LongReal(sum));
  IO.Put("\n");
END Sum.


program Sum3sAnd5s;

function Multiple(x, y: integer): Boolean;
  { Is X a multiple of Y? }
   begin
      Multiple := (X mod Y) = 0
   end;

function SumMultiples(n: integer): longint;
  { Return the sum of all multiples of 3 or 5. }
   var i: integer; sum: longint;
   begin
      sum := 0;
      for i := 1 to pred(n) do
         if Multiple(i, 3) or Multiple(i, 5) then
           sum := sum + i;
      SumMultiples := sum
   end;

begin
   { Show sum of all multiples less than 1000. }
   writeln(SumMultiples(1000))
end.


#!/usr/bin/perl
use v5.20;
use experimental qw(signatures);

use List::Util qw( sum ) ;

sub sum_3_5($limit) {
   return sum grep { $_ % 3 == 0 || $_ % 5 == 0 } ( 1..$limit - 1 ) ;
}

say "The sum is ${\(sum_3_5 1000)}!\n" ;


SOAS(N)
 NEW SUM,I SET SUM=0
 FOR I=1:1:N DO
 .SET SUM=SUM+(1/((I*I)))
 QUIT SUM


(let (s 0)
  (for (i 1 1000)
    (inc s (div 1 (* i i))))
  (println s))


function sumMul(atom n, f)
    n = floor((n-1)/f)
    return f*n*(n+1)/2
end function

function sum35(atom n)
    return sumMul(n,3) +
           sumMul(n,5) -
           sumMul(n,15)
end function

for i=0 to 8 do
    string sp = repeat(' ',9-i),
           pt = "1"&repeat('0',i)
    printf(1,"%s%s%s %d\n",{sp,pt,sp,sum35(power(10,i))})
end for


bundle Default {
  class SumSeries {
    function : Main(args : String[]) ~ Nil {
      DoSumSeries();
    }

    function : native : DoSumSeries() ~ Nil {
      start := 1;
      end := 1000;

      sum := 0.0;

      for(x : Float := start; x <= end; x += 1;) {
        sum += f(x);
      };

      IO.Console->GetInstance()->Print("Sum of f(x) from ")->Print(start)->Print(" to ")->Print(end)->Print(" is ")->PrintLine(sum);
    }

    function : native : f(x : Float) ~ Float {
      return 1.0 / (x * x);
    }
  }
}


V arr = [1, 2, 3, 4]
print(sum(arr))
print(product(arr))


sumdiv(N, D) = S =>
    M = N div D,
    S = (M*(M + 1) div 2) * D.

sum35big(N) = sumdiv(N, 3) + sumdiv(N, 5) - sumdiv(N, 15).

main =>
    Upto1K = [N: N in 1..999, (N mod 3 = 0; N mod 5 = 0)].sum,
    writef("The sum of all multiples of 3 and 5 below 1000 is %w%n", Upto1K),
    writef("The sum of all multiples less than 1e20 is %w%n", sum35big(99999_99999_99999_99999)).


(de sumMul (N F)
   (let N1 (/ (dec N) F)
      (*/ F N1 (inc N1) 2) ) )

(for I 20
   (let N (** 10 I)
      (println
         (-
            (+ (sumMul N 3) (sumMul N 5))
            (sumMul N 15) ) ) ) )


threeor5: procedure options (main);      /* 8 June 2014 */
   declare (i, n) fixed(10), sum fixed (31) static initial (0);

   get (n);
   put ('The number of multiples of 3 or 5 below ' || trim(n) || ' is');

   do i = 1 to n-1;
      if mod(i, 3) = 0 | mod(i, 5) = 0 then sum = sum + i;
   end;

   put edit ( trim(sum) ) (A);

end threeor5;


F counter(arr)
   DefaultDict[Int, Int] d
   L(a) arr
      d[a]++
   R d

F decompose_sum(s)
   R (2 .< Int(s / 2 + 1)).map(a -> (a, @s - a))

Set[(Int, Int)] all_pairs_set
L(a) 2..99
   L(b) a + 1 .< 100
      I a + b < 100
         all_pairs_set.add((a, b))
V all_pairs = Array(all_pairs_set)

V product_counts = counter(all_pairs.map((c, d) -> c * d))
V unique_products = Set(all_pairs.filter((a, b) -> :product_counts[a * b] == 1))
V s_pairs = all_pairs.filter((a, b) -> all(decompose_sum(a + b).map((x, y) -> (x, y) !C :unique_products)))

product_counts = counter(s_pairs.map((c, d) -> c * d))
V p_pairs = s_pairs.filter((a, b) -> :product_counts[a * b] == 1)

V sum_counts = counter(p_pairs.map((c, d) -> c + d))
V final_pairs = p_pairs.filter((a, b) -> :sum_counts[a + b] == 1)

print(final_pairs)


let sum a b fn =
  let result = ref 0. in
  for i = a to b do
    result := !result +. fn i
  done;
  !result


: sumSerie(s, n)   0 n seq apply(#[ s perform + ]) ;


*        Sum and product of an array  20/04/2017
SUMPROD  CSECT
         USING  SUMPROD,R15        base register
         SR     R3,R3              su=0
         LA     R5,1               pr=1
         LA     R6,1               i=1
       DO WHILE=(CH,R6,LE,=AL2((PG-A)/4))  do i=1 to hbound(a)
         LR     R1,R6                i
         SLA    R1,2                 *4
         A      R3,A-4(R1)           su=su+a(i)
         M      R4,A-4(R1)           pr=pr*a(i)
         LA     R6,1(R6)             i++
       ENDDO    ,                  enddo i
         XDECO  R3,PG              su
         XDECO  R5,PG+12           pr
         XPRNT  PG,L'PG            print
         BR     R14                exit
A        DC     F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10'
PG       DS     CL24               buffer
         YREGS
         END    SUMPROD


ARRAY INTEGER($list;0)
For ($i;1;5)
       APPEND TO ARRAY($list;$i)
End for

$sum:=0
$product:=1
For ($i;1;Size of array($list))
   $sum:=$var+$list{$i}
   $product:=$product*$list{$i}
End for

// since 4D v13

$sum:=sum($list)


(defun sum (xs)
   (if (endp xs)
       0
       (+ (first xs)
          (sum (rest xs)))))

(defun prod (xs)
   (if (endp xs)
       1
       (* (first xs)
          (prod (rest xs)))))


function SumMultiples ( [int]$Base, [int]$Upto )
    {
    $X = ($Upto - ( $Upto % $Base ) ) / $Base + ( [int] ( $Upto % $Base -ne 0 ) )
    $Sum = ( $X * $X - $X ) * $Base / 2
    Return $Sum
    }

#  Calculate the sum of the multiples of 3 and 5 up to 1000
( SumMultiples -Base 3 -Upto 1000 ) + ( SumMultiples -Base 5 -Upto 1000 ) - ( SumMultiples -Base 15 -Upto 1000 )


sum_of_multiples_of_3_and_5_slow(N, TT) :-
	sum_of_multiples_of_3_and_5(N, 1, 0, TT).

sum_of_multiples_of_3_and_5(N, K, S, S) :-
	3 * K >= N.

sum_of_multiples_of_3_and_5(N, K, C, S) :-
	T3 is 3 * K, T3 < N,
	C3 is C + T3,
	T5 is 5 * K,
	(   (T5 < N, K mod 3 =\= 0)
	->  C5 is C3 + T5
	;   C5 = C3),
	K1 is K+1,
	sum_of_multiples_of_3_and_5(N, K1, C5, S).


# syntax: GAWK -f SUM_AND_PRODUCT_PUZZLE.AWK
BEGIN {
    for (s=2; s<=100; s++) {
      if ((a=satisfies_statement3(s)) != 0) {
        printf("%d (%d+%d)\n",s,a,s-a)
      }
    }
    exit(0)
}
function satisfies_statement1(s,  a) { # S says: P does not know the two numbers.
# Given s, for all pairs (a,b), a+b=s, 2 <= a,b <= 99, true if at least one of a or b is composite
    for (a=2; a<=int(s/2); a++) {
      if (is_prime(a) && is_prime(s-a)) {
        return(0)
      }
    }
    return(1)
}
function satisfies_statement2(p,  i,j,winner) { # P says: Now I know the two numbers.
# Given p, for all pairs (a,b), a*b=p, 2 <= a,b <= 99, true if exactly one pair satisfies statement 1
    for (i=2; i<=int(sqrt(p)); i++) {
      if (p % i == 0) {
        j = int(p/i)
        if (!(2 <= j && j <= 99)) { # in range
          continue
        }
        if (satisfies_statement1(i+j)) {
          if (winner) {
            return(0)
          }
          winner = 1
        }
      }
    }
    return(winner)
}
function satisfies_statement3(s,  a,b,winner) { # S says: Now I know the two numbers.
# Given s, for all pairs (a,b), a+b=s, 2 <= a,b <= 99, true if exactly one pair satisfies statements 1 and 2
    if (!satisfies_statement1(s)) {
      return(0)
    }
    for (a=2; a<=int(s/2); a++) {
      b = s - a
      if (satisfies_statement2(a*b)) {
        if (winner) {
          return(0)
        }
        winner = a
      }
    }
    return(winner)
}
function is_prime(x,  i) {
    if (x <= 1) {
      return(0)
    }
    for (i=2; i<=int(sqrt(x)); i++) {
      if (x % i == 0) {
        return(0)
      }
    }
    return(1)
}


DEF VAR dcResult AS DECIMAL NO-UNDO.
DEF VAR n AS INT NO-UNDO.

DO n = 1 TO 1000 :
  dcResult = dcResult + 1 / (n * n)  .
END.

DISPLAY dcResult .


declare
  fun {SumSeries S N}
     {FoldL {Map {List.number 1 N 1} S}
      Number.'+' 0.}
  end

  fun {S X}
     1. / {Int.toFloat X*X}
  end
in
  {Show {SumSeries S 1000}}


DEFINE LAST="6"

PROC Main()
  INT ARRAY data=[1 2 3 4 5 6 7]
  BYTE i
  INT a,res

  res=0
  FOR i=0 TO LAST
  DO
    a=data(i)
    PrintI(a)
    IF i=LAST THEN
      Put('=)
    ELSE
      Put('+)
    FI
    res==+a
  OD
  PrintIE(res)

  res=1
  FOR i=0 TO LAST
  DO
    a=data(i)
    PrintI(a)
    IF i=LAST THEN
      Put('=)
    ELSE
      Put('*)
    FI
    res=res*a
  OD
  PrintIE(res)
RETURN


package {
	import flash.display.Sprite;

	public class SumAndProduct extends Sprite
	{
		public function SumAndProduct()
		{
			var arr:Array = [1, 2, 3, 4, 5];
			var sum:int = 0;
			var prod:int = 1;

			for (var i:int = 0; i < arr.length; i++)
			{
				sum += arr[i];
				prod *= arr[i];
			}

			trace("Sum: " + sum); // 15
			trace("Product: " + prod); // 120
		}
	}
}


type Int_Array is array(Integer range <>) of Integer;

array : Int_Array := (1,2,3,4,5,6,7,8,9,10);
Sum : Integer := 0;
for I in array'range loop
   Sum := Sum + array(I);
end loop;


EnableExplicit

Procedure.q SumMultiples(Limit.q)
  If Limit < 0 : Limit = -Limit : EndIf; convert negative numbers to positive
  Protected.q i, sum = 0
  For i = 3 To Limit - 1
    If i % 3 = 0 Or i % 5 = 0
      sum + i
    EndIf
  Next
  ProcedureReturn sum
EndProcedure

If OpenConsole()
  PrintN("Sum of numbers below 1000 which are multiples of 3 or 5 is : " + SumMultiples(1000))
  PrintN("")
  PrintN("Press any key to close the console")
  Repeat: Delay(10) : Until Inkey() <> ""
  CloseConsole()
EndIf


def sum35a(n):
    'Direct count'
    # note: ranges go to n-1
    return sum(x for x in range(n) if x%3==0 or x%5==0)

def sum35b(n):
    "Count all the 3's; all the 5's; minus double-counted 3*5's"
    # note: ranges go to n-1
    return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15))

def sum35c(n):
    'Sum the arithmetic progressions: sum3 + sum5 - sum15'
    consts = (3, 5, 15)
    # Note: stop at n-1
    divs = [(n-1) // c for c in consts]
    sums = [d*c*(1+d)/2 for d,c in zip(divs, consts)]
    return sums[0] + sums[1] - sums[2]

#test
for n in range(1001):
    sa, sb, sc = sum35a(n), sum35b(n), sum35c(n)
    assert sa == sb == sc  # python tests aren't like those of c.

print('For n = %7i -> %i\n' % (n, sc))

# Pretty patterns
for p in range(7):
    print('For n = %7i -> %i' % (10**p, sum35c(10**p)))

# Scalability
p = 20
print('\nFor n = %20i -> %i' % (10**p, sum35c(10**p)))


#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct node_t {
    int x, y;
    struct node_t *prev, *next;
} node;

node *new_node(int x, int y) {
    node *n = malloc(sizeof(node));
    n->x = x;
    n->y = y;
    n->next = NULL;
    n->prev = NULL;
    return n;
}

void free_node(node **n) {
    if (n == NULL) {
        return;
    }

    (*n)->prev = NULL;
    (*n)->next = NULL;

    free(*n);

    *n = NULL;
}

typedef struct list_t {
    node *head;
    node *tail;
} list;

list make_list() {
    list lst = { NULL, NULL };
    return lst;
}

void append_node(list *const lst, int x, int y) {
    if (lst == NULL) {
        return;
    }

    node *n = new_node(x, y);

    if (lst->head == NULL) {
        lst->head = n;
        lst->tail = n;
    } else {
        n->prev = lst->tail;
        lst->tail->next = n;
        lst->tail = n;
    }
}

void remove_node(list *const lst, const node *const n) {
    if (lst == NULL || n == NULL) {
        return;
    }

    if (n->prev != NULL) {
        n->prev->next = n->next;
        if (n->next != NULL) {
            n->next->prev = n->prev;
        } else {
            lst->tail = n->prev;
        }
    } else {
        if (n->next != NULL) {
            n->next->prev = NULL;
            lst->head = n->next;
        }
    }

    free_node(&n);
}

void free_list(list *const lst) {
    node *ptr;

    if (lst == NULL) {
        return;
    }
    ptr = lst->head;

    while (ptr != NULL) {
        node *nxt = ptr->next;
        free_node(&ptr);
        ptr = nxt;
    }

    lst->head = NULL;
    lst->tail = NULL;
}

void print_list(const list *lst) {
    node *it;

    if (lst == NULL) {
        return;
    }

    for (it = lst->head; it != NULL; it = it->next) {
        int sum = it->x + it->y;
        int prod = it->x * it->y;
        printf("[%d, %d] S=%d P=%d\n", it->x, it->y, sum, prod);
    }
}

void print_count(const list *const lst) {
    node *it;
    int c = 0;

    if (lst == NULL) {
        return;
    }

    for (it = lst->head; it != NULL; it = it->next) {
        c++;
    }

    if (c == 0) {
        printf("no candidates\n");
    } else    if (c == 1) {
        printf("one candidate\n");
    } else {
        printf("%d candidates\n", c);
    }
}

void setup(list *const lst) {
    int x, y;

    if (lst == NULL) {
        return;
    }

    // numbers must be greater than 1
    for (x = 2; x <= 98; x++) {
        // numbers must be unique, and sum no more than 100
        for (y = x + 1; y <= 98; y++) {
            if (x + y <= 100) {
                append_node(lst, x, y);
            }
        }
    }
}

void remove_by_sum(list *const lst, const int sum) {
    node *it;

    if (lst == NULL) {
        return;
    }

    it = lst->head;
    while (it != NULL) {
        int s = it->x + it->y;

        if (s == sum) {
            remove_node(lst, it);
            it = lst->head;
        } else {
            it = it->next;
        }
    }
}

void remove_by_prod(list *const lst, const int prod) {
    node *it;

    if (lst == NULL) {
        return;
    }

    it = lst->head;
    while (it != NULL) {
        int p = it->x * it->y;

        if (p == prod) {
            remove_node(lst, it);
            it = lst->head;
        } else {
            it = it->next;
        }
    }
}

void statement1(list *const lst) {
    short *unique = calloc(100000, sizeof(short));
    node *it, *nxt;

    for (it = lst->head; it != NULL; it = it->next) {
        int prod = it->x * it->y;
        unique[prod]++;
    }

    it = lst->head;
    while (it != NULL) {
        int prod = it->x * it->y;
        nxt = it->next;
        if (unique[prod] == 1) {
            remove_by_sum(lst, it->x + it->y);
            it = lst->head;
        } else {
            it = nxt;
        }
    }

    free(unique);
}

void statement2(list *const candidates) {
    short *unique = calloc(100000, sizeof(short));
    node *it, *nxt;

    for (it = candidates->head; it != NULL; it = it->next) {
        int prod = it->x * it->y;
        unique[prod]++;
    }

    it = candidates->head;
    while (it != NULL) {
        int prod = it->x * it->y;
        nxt = it->next;
        if (unique[prod] > 1) {
            remove_by_prod(candidates, prod);
            it = candidates->head;
        } else {
            it = nxt;
        }
    }

    free(unique);
}

void statement3(list *const candidates) {
    short *unique = calloc(100, sizeof(short));
    node *it, *nxt;

    for (it = candidates->head; it != NULL; it = it->next) {
        int sum = it->x + it->y;
        unique[sum]++;
    }

    it = candidates->head;
    while (it != NULL) {
        int sum = it->x + it->y;
        nxt = it->next;
        if (unique[sum] > 1) {
            remove_by_sum(candidates, sum);
            it = candidates->head;
        } else {
            it = nxt;
        }
    }

    free(unique);
}

int main() {
    list candidates = make_list();

    setup(&candidates);
    print_count(&candidates);

    statement1(&candidates);
    print_count(&candidates);

    statement2(&candidates);
    print_count(&candidates);

    statement3(&candidates);
    print_count(&candidates);

    print_list(&candidates);

    free_list(&candidates);
    return 0;
}


Program SumSeries;
type
  tOutput = double;//extended;
  tmyFunc = function(number: LongInt): tOutput;

function f(number: LongInt): tOutput;
begin
  f := 1/sqr(tOutput(number));
end;

function Sum(from,upto: LongInt;func:tmyFunc):tOutput;
var
  res: tOutput;
begin
  res := 0.0;
//  for from:= from to upto do res := res + f(from);
  for upTo := upto downto from do res := res + f(upTo);
  Sum := res;
end;

BEGIN
  writeln('The sum of 1/x^2 from 1 to 1000 is: ', Sum(1,1000,@f));
  writeln('Whereas pi^2/6 is:                  ', pi*pi/6:10:8);
end.


void
compute(integer &s, integer &p, list l)
{
    integer v;

    s = 0;
    p = 1;
    for (, v in l) {
        s += v;
        p *= v;
    }
}

integer
main(void)
{
    integer sum, product;

    compute(sum, product, list(2, 3, 5, 7, 11, 13, 17, 19));

    o_form("~\n~\n", sum, product);

    return 0;
}


main:(
  INT default upb := 3;
  MODE INTARRAY = [default upb]INT;

  INTARRAY array = (1,2,3,4,5,6,7,8,9,10);
  INT sum := 0;
  FOR i FROM LWB array TO UPB array DO
     sum +:= array[i]
  OD;

  # Define the product function #
  PROC int product = (INTARRAY item)INT:
  (
    INT prod :=1;
    FOR i FROM LWB item TO UPB item DO
       prod *:= item[i]
    OD;
    prod
  ) # int product # ;
  printf(($" Sum: "g(0)$,sum,$", Product:"g(0)";"l$,int product(array)))
)


begin

    % computes the sum and product of intArray                               %
    % the results are returned in sum and product                            %
    % the bounds of the array must be specified in lb and ub                 %
    procedure sumAndProduct( integer array  intArray ( * )
                           ; integer value  lb, ub
                           ; integer result sum, product
                           ) ;
    begin

        sum     := 0;
        product := 1;

        for i := lb until ub
        do begin
            sum     :=     sum + intArray( i );
            product := product * intArray( i );
        end for_i ;

    end sumAndProduct ;

    % test the sumAndProduct procedure                                       %
    begin

        integer array v   ( 1 :: 10 );
        integer sum, product;

        for i := 1 until 10 do v( i ) := i;

        sumAndProduct( v, 1, 10, sum, product );
        write( sum, product );
    end
end.


  [ dup 1+ * 2 / ]                  is triangulared ( n --> n )

  [ 1 -
    dup   3 / triangulared  3 *
    over  5 / triangulared  5 * +
    swap 15 / triangulared 15 * - ] is sum-of-3s&5s ( n --> n )

      1000 sum-of-3s&5s echo cr

  10 20 ** sum-of-3s&5s echo cr


#include <algorithm>
#include <iostream>
#include <map>
#include <vector>

std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {
    for (auto &p : v) {
        auto sum = p.first + p.second;
        auto prod = p.first * p.second;
        os << '[' << p.first << ", " << p.second << "] S=" << sum << " P=" << prod;
    }
    return os << '\n';
}

void print_count(const std::vector<std::pair<int, int>> &candidates) {
    auto c = candidates.size();
    if (c == 0) {
        std::cout << "no candidates\n";
    } else if (c == 1) {
        std::cout << "one candidate\n";
    } else {
        std::cout << c << " candidates\n";
    }
}

auto setup() {
    std::vector<std::pair<int, int>> candidates;

    // numbers must be greater than 1
    for (int x = 2; x <= 98; x++) {
        // numbers must be unique, and sum no more than 100
        for (int y = x + 1; y <= 98; y++) {
            if (x + y <= 100) {
                candidates.push_back(std::make_pair(x, y));
            }
        }
    }

    return candidates;
}

void remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {
    candidates.erase(std::remove_if(
        candidates.begin(), candidates.end(),
        [sum](const std::pair<int, int> &pair) {
            auto s = pair.first + pair.second;
            return s == sum;
        }
    ), candidates.end());
}

void remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {
    candidates.erase(std::remove_if(
        candidates.begin(), candidates.end(),
        [prod](const std::pair<int, int> &pair) {
            auto p = pair.first * pair.second;
            return p == prod;
        }
    ), candidates.end());
}

void statement1(std::vector<std::pair<int, int>> &candidates) {
    std::map<int, int> uniqueMap;

    std::for_each(
        candidates.cbegin(), candidates.cend(),
        [&uniqueMap](const std::pair<int, int> &pair) {
            auto prod = pair.first * pair.second;
            uniqueMap[prod]++;
        }
    );

    bool loop;
    do {
        loop = false;
        for (auto &pair : candidates) {
            auto prod = pair.first * pair.second;
            if (uniqueMap[prod] == 1) {
                auto sum = pair.first + pair.second;
                remove_by_sum(candidates, sum);

                loop = true;
                break;
            }
        }
    } while (loop);
}

void statement2(std::vector<std::pair<int, int>> &candidates) {
    std::map<int, int> uniqueMap;

    std::for_each(
        candidates.cbegin(), candidates.cend(),
        [&uniqueMap](const std::pair<int, int> &pair) {
            auto prod = pair.first * pair.second;
            uniqueMap[prod]++;
        }
    );

    bool loop;
    do {
        loop = false;
        for (auto &pair : candidates) {
            auto prod = pair.first * pair.second;
            if (uniqueMap[prod] > 1) {
                remove_by_prod(candidates, prod);

                loop = true;
                break;
            }
        }
    } while (loop);
}

void statement3(std::vector<std::pair<int, int>> &candidates) {
    std::map<int, int> uniqueMap;

    std::for_each(
        candidates.cbegin(), candidates.cend(),
        [&uniqueMap](const std::pair<int, int> &pair) {
            auto sum = pair.first + pair.second;
            uniqueMap[sum]++;
        }
    );

    bool loop;
    do {
        loop = false;
        for (auto &pair : candidates) {
            auto sum = pair.first + pair.second;
            if (uniqueMap[sum] > 1) {
                remove_by_sum(candidates, sum);

                loop = true;
                break;
            }
        }
    } while (loop);
}

int main() {
    auto candidates = setup();
    print_count(candidates);

    statement1(candidates);
    print_count(candidates);

    statement2(candidates);
    print_count(candidates);

    statement3(candidates);
    print_count(candidates);

    std::cout << candidates;

    return 0;
}


function sumto(atom n)
    atom res = 0
    for i=1 to n do
        res += 1/(i*i)
    end for
    return res
end function
?sumto(1000)


<?php

/**
 * @author Elad Yosifon
 */

/**
 * @param int $n
 * @param int $k
 * @return float|int
 */
function sum_of_a_series($n,$k)
{
	$sum_of_a_series = 0;
	for($i=$k;$i<=$n;$i++)
	{
		$sum_of_a_series += (1/($i*$i));
	}
	return $sum_of_a_series;
}

echo sum_of_a_series(1000,1);


      sum  ←  +/
      prod ←  ×/

      list ←  1 2 3 4 5

      sum  list
15

      prod list
120


set array to {1, 2, 3, 4, 5}
set sum to 0
set product to 1
repeat with i in array
    set sum to sum + i
    set product to product * i
end repeat


arr: 1..10

print ["Sum =" sum arr]
print ["Product =" product arr]


#lang racket
(require math)

;;; A naive solution
(define (naive k)
  (for/sum ([n (expt 10 k)]
            #:when (or (divides? 3 n) (divides? 5 n)))
    n))

(for/list ([k 7]) (naive k))

;;; Using the formula for an arithmetic sum
(define (arithmetic-sum a1 n Δa)
  ; returns a1+a2+...+an
  (define an (+ a1 (* (- n 1) Δa)))
  (/ (* n (+ a1 an)) 2))

(define (analytical k)
  (define 10^k (expt 10 k))
  (define (n d) (quotient (- 10^k 1) d))
  (+    (arithmetic-sum  3 (n  3)  3)
        (arithmetic-sum  5 (n  5)  5)
     (- (arithmetic-sum 15 (n 15) 15))))

(for/list ([k 20]) (analytical k))


using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        const int maxSum = 100;
        var pairs = (
            from X in 2.To(maxSum / 2 - 1)
            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)
            select new { X, Y, S = X + Y, P = X * Y }
            ).ToHashSet();

        Console.WriteLine(pairs.Count);

        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();

        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));
        Console.WriteLine(pairs.Count);

        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));
        Console.WriteLine(pairs.Count);

        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));
        Console.WriteLine(pairs.Count);

        foreach (var pair in pairs) Console.WriteLine(pair);
    }
}

public static class Extensions
{
    public static IEnumerable<int> To(this int start, int end) {
        for (int i = start; i <= end; i++) yield return i;
    }

    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);
}


(scl 9)  # Calculate with 9 digits precision

(let S 0
   (for I 1000
      (inc 'S (*/ 1.0 (* I I))) )
   (prinl (round S 6)) )  # Round result to 6 digits


int[] matriz = {1,2,3,4,5};
int suma = 0, prod = 1;

for (int p : matriz) {
  suma += p;
  prod *= p;
}
write("Sum = ", suma);
write("Product = ", prod);


numbers = 1,2,3,4,5
product := 1
loop, parse, numbers, `,
{
sum += A_LoopField
product *= A_LoopField
}
msgbox, sum = %sum%`nproduct = %product%


$ awk 'func sum(s){split(s,a);r=0;for(i in a)r+=a[i];return r}{print sum($0)}'
1 2 3 4 5 6 7 8 9 10
55

$ awk 'func prod(s){split(s,a);r=1;for(i in a)r*=a[i];return r}{print prod($0)}'
1 2 3 4 5 6 7 8 9 10
3628800


see sum35(1000) + nl

func sum35 n
     n = n - 1
     return(3 * tri(floor(n / 3)) +
	    5 * tri(floor(n / 5)) -
	    15 * tri(floor(n / 15)))

func tri n
     return n * (n + 1) / 2


print multSum35(1000)
end
function multSum35(n)
    for i = 1 to n - 1
        If (i mod 3 = 0) or (i mod 5 = 0) then  multSum35 = multSum35 + i
    next i
end function


;;; Calculate all x's and their possible y's.
(defparameter *x-possibleys*
  (loop for x from 2 to 49
     collect (cons x (loop for y from (- 100 x) downto (1+ x)
			collect y)))
  "For every x there are certain y's, with respect to the rules of the puzzle")

(defun xys-operation (op x-possibleys)
  "returns an alist of ((x possible-y) . (op x possible-y))"
  (let ((x (car x-possibleys))
	(ys (cdr x-possibleys)))
    (mapcar #'(lambda (y) (cons (list x y) (funcall op x y))) ys)))

(defun sp-numbers (op x-possibleys)
  "generates all possible sums or products of the puzzle"
  (loop for xys in x-possibleys
       append (xys-operation op xys)))

(defun group-sp (sp-numbers)
  "sp: Sum or Product"
  (loop for sp-number in (remove-duplicates sp-numbers :key #'cdr)
     collect (cons (cdr sp-number)
		   (mapcar #'car
			   (remove-if-not
			    #'(lambda (sp) (= sp (cdr sp-number)))
			    sp-numbers
			    :key #'cdr)))))

(defun statement-1a (sum-groups)
  "remove all sums with a single possible xy"
  (remove-if
   #'(lambda (xys) (= (list-length xys) 1))
   sum-groups
   :key #'cdr))

(defun statement-1b (x-possibleys)
  "S says: P does not know X and Y."
  (let ((multi-xy-sums (statement-1a (group-sp (sp-numbers #'+ x-possibleys))))
	(products (group-sp (sp-numbers #'* x-possibleys))))
    (flet ((sum-has-xy-which-leads-to-unique-prod (sum-xys)
	     ;; is there any product with a single possible xy?
	     (some #'(lambda (prod-xys) (= (list-length (cdr prod-xys)) 1))
		   ;; all possible xys of the sum's (* x ys)
		   (mapcar #'(lambda (xy) (assoc (apply #'* xy) products))
			   (cdr sum-xys)))))
      ;; remove sums with even one xy which leads to a unique product
      (remove-if #'sum-has-xy-which-leads-to-unique-prod multi-xy-sums))))

(defun remaining-products (remaining-sums-xys)
  "P's number is one of these"
  (loop for sum-xys in remaining-sums-xys
     append (loop for xy in (cdr sum-xys)
	       collect (apply #'* xy))))

(defun statement-2 (remaining-sums-xys)
  "P says: Now I know X and Y."
  (let ((remaining-products (remaining-products remaining-sums-xys)))
    (mapcar #'(lambda (a-sum-unit)
		(cons (car a-sum-unit)
		      (mapcar #'(lambda (xy)
				  (list (count (apply #'* xy) remaining-products)
					xy))
			      (cdr a-sum-unit))))
	    remaining-sums-xys)))

(defun statement-3 (remaining-sums-with-their-products-occurrences-info)
  "S says: Now I also know X and Y."
  (remove-if
   #'(lambda (sum-xys)
       ;; remove those sums which have more than 1 product, that
       ;; appear only once amongst all remaining products
       (> (count 1 sum-xys :key #'car) 1))
   remaining-sums-with-their-products-occurrences-info
   :key #'cdr))

(defun solution (survivor-sum-and-its-xys)
  "Now we know X and Y too :-D"
  (let* ((sum (caar survivor-sum-and-its-xys))
	 (xys (cdar survivor-sum-and-its-xys))
	 (xy (second (find 1 xys :key #'car))))
    (pairlis '(x y sum product)
	     (list (first xy) (second xy) sum (apply #'* xy)))))

(solution
 (statement-3
  (statement-2
   (statement-1b *x-possibleys*)))) ;; => ((PRODUCT . 52) (SUM . 17) (Y . 13) (X . 4))


/* sum the first 1000 terms of the series 1/n**2. */
s = 0;

do i = 1000 to 1 by -1;
   s = s + 1/float(i**2);
end;

put skip list (s);


lvars s = 0, j;
for j from 1 to 1000 do
    s + 1.0/(j*j) -> s;
endfor;

s =>


/aproxriemann{
/x exch def
/i 1 def
/sum 0 def
x{
/sum sum i -2 exp add def
/i i 1 add def
}repeat
sum ==
}def

1000 aproxriemann


main: { [2 3 5 7 11 13] sp }

sum!    : { <- 0 -> { + } eachar }
product!: { <- 1 -> { * } eachar }

sp!:
    { dup
    sum %d cr <<
    product %d cr << }

Result:
41
30030


dim array(5) as integer = { 1, 2, 3, 4, 5 }

dim sum as integer = 0
dim prod as integer = 1
for index as integer = lbound(array) to ubound(array)
  sum += array(index)
  prod *= array(index)
next


arraybase 1
dim array(5)
array[1] = 1
array[2] = 2
array[3] = 3
array[4] = 4
array[5] = 5

sum = 0
prod = 1
for index = 1 to array[?]
	sum += array[index]
	prod *= array[index]
next index
print "The sum is "; sum            #15
print "and the product is "; prod   #120
end


extern crate rug;

use rug::Integer;
use rug::ops::Pow;

fn main() {
    for i in [3, 20, 100, 1_000].iter() {
        let ten = Integer::from(10);
        let mut limit = Integer::from(Integer::from(&ten.pow(*i as u32)) - 1);
        let mut aux_3_1 = &limit.mod_u(3u32);
        let mut aux_3_2 = Integer::from(&limit - aux_3_1);
        let mut aux_3_3 = Integer::from(&aux_3_2/3);
        let mut aux_3_4 = Integer::from(3 + aux_3_2);
        let mut aux_3_5 = Integer::from(&aux_3_3*&aux_3_4);
        let mut aux_3_6 = Integer::from(&aux_3_5/2);

        let mut aux_5_1 = &limit.mod_u(5u32);
        let mut aux_5_2 = Integer::from(&limit - aux_5_1);
        let mut aux_5_3 = Integer::from(&aux_5_2/5);
        let mut aux_5_4 = Integer::from(5 + aux_5_2);
        let mut aux_5_5 = Integer::from(&aux_5_3*&aux_5_4);
        let mut aux_5_6 = Integer::from(&aux_5_5/2);

        let mut aux_15_1 = &limit.mod_u(15u32);
        let mut aux_15_2 = Integer::from(&limit - aux_15_1);
        let mut aux_15_3 = Integer::from(&aux_15_2/15);
        let mut aux_15_4 = Integer::from(15 + aux_15_2);
        let mut aux_15_5 = Integer::from(&aux_15_3*&aux_15_4);
        let mut aux_15_6 = Integer::from(&aux_15_5/2);

        let mut result_aux_1 = Integer::from(&aux_3_6 + &aux_5_6);
        let mut result = Integer::from(&result_aux_1 - &aux_15_6);

        println!("Sum for 10^{} : {}",i,result);
    }
}


def sum35( max:BigInt ) : BigInt = max match {

  // Simplest solution but limited to Ints only
  case j if j < 100000 => (1 until j.toInt).filter( i => i % 3 == 0 || i % 5 == 0 ).sum

  // Using a custom iterator that takes Longs
  case j if j < 10e9.toLong => {
    def stepBy( step:Long ) : Iterator[Long] = new Iterator[Long] { private var i = step; def hasNext = true; def next() : Long = { val result = i; i = i + step; result } }
    stepBy(3).takeWhile( _< j ).sum + stepBy(5).takeWhile( _< j ).sum - stepBy(15).takeWhile( _< j ).sum
  }

  // Using the formula for a Triangular number
  case j => {
    def triangle( i:BigInt ) = i * (i+1) / BigInt(2)
    3 * triangle( (j-1)/3 ) + 5 * triangle( (j-1)/5 ) - 15 * triangle( (j-1)/15 )
  }
}

{
for( i <- (0 to 20); n = "1"+"0"*i ) println( (" " * (21 - i)) + n + " => " + (" " * (21 - i)) + sum35(BigInt(n)) )
}


void main() {
    import std.stdio, std.algorithm, std.range, std.typecons;

    const s1 = cartesianProduct(iota(1, 101), iota(1, 101))
               .filter!(p => 1 < p[0] && p[0] < p[1] && p[0] + p[1] < 100)
               .array;

    alias P = const Tuple!(int, int);
    enum add   = (P p) => p[0] + p[1];
    enum mul   = (P p) => p[0] * p[1];
    enum sumEq = (P p) => s1.filter!(q => add(q) == add(p));
    enum mulEq = (P p) => s1.filter!(q => mul(q) == mul(p));

    const s2 = s1.filter!(p => sumEq(p).all!(q => mulEq(q).walkLength != 1)).array;
    const s3 = s2.filter!(p => mulEq(p).setIntersection(s2).walkLength == 1).array;
    s3.filter!(p => sumEq(p).setIntersection(s3).walkLength == 1).writeln;
}


defmodule Puzzle do
  def sum_and_product do
    s1 = for x <- 2..49, y <- x+1..99, x+y<100, do: {x,y}
    s2 = Enum.filter(s1, fn p ->
      Enum.all?(sumEq(s1,p), fn q -> length(mulEq(s1,q)) != 1 end)
    end)
    s3 = Enum.filter(s2, fn p -> only1?(mulEq(s1,p), s2) end)
    Enum.filter(s3, fn p -> only1?(sumEq(s1,p), s3) end) |> IO.inspect
  end

  defp add({x,y}), do: x + y

  defp mul({x,y}), do: x * y

  defp sumEq(s, p), do: Enum.filter(s, fn q -> add(p) == add(q) end)

  defp mulEq(s, p), do: Enum.filter(s, fn q -> mul(p) == mul(q) end)

  defp only1?(a, b) do
    MapSet.size(MapSet.intersection(MapSet.new(a), MapSet.new(b))) == 1
  end
end

Puzzle.sum_and_product


sum = 0.0
1 to 1000 (i): sum = sum + 1.0 / (i * i).
sum print


$x = 1..1000 `
       | ForEach-Object { 1 / ($_ * $_) } `
       | Measure-Object -Sum
Write-Host Sum = $x.Sum


sum(S) :-
        findall(L, (between(1,1000,N),L is 1/N^2), Ls),
        sumlist(Ls, S).


    SumProd ← +´⋈×´
+´⋈×´
   SumProd 1‿2‿3‿4‿5
⟨ 15 120 ⟩


(fold (lambda (x tot) (+ tot (if (or (zero? (remainder x 3)) (zero? (remainder x 5))) x 0))) 0 (iota 1000))


$ include "seed7_05.s7i";
  include "bigint.s7i";

const func bigInteger: sum35 (in bigInteger: n) is func
  result
    var bigInteger: sum35 is 0_;
  local
    const func bigInteger: sumMul (in bigInteger: n, in bigInteger: f) is func
      result
        var bigInteger: sumMul is 0_;
      local
        var bigInteger: n1 is 0_;
      begin
        n1 := pred(n) div f;
        sumMul := f * n1 * succ(n1) div 2_;
      end func;
   begin
     sum35 := sumMul(n, 3_) + sumMul(n, 5_) - sumMul(n, 15_);
   end func;

const proc: main is func
  begin
    writeln(sum35(1000_));
    writeln(sum35(10_ ** 20));
  end func;


USING: combinators.short-circuit fry kernel literals math
math.ranges memoize prettyprint sequences sets tools.time ;
IN: rosetta-code.sum-and-product

CONSTANT: s1 $[
    2 100 [a,b] dup cartesian-product concat
    [ first2 { [ < ] [ + 100 < ] } 2&& ] filter
]

: quot-eq ( pair quot -- seq )
    [ s1 ] 2dip tuck '[ @ _ @ = ] filter ; inline

MEMO: sum-eq ( pair -- seq ) [ first2 + ] quot-eq ;
MEMO: mul-eq ( pair -- seq ) [ first2 * ] quot-eq ;

: s2 ( -- seq )
    s1 [ sum-eq [ mul-eq length 1 = not ] all? ] filter ;

: only-1 ( seq quot -- newseq )
    over '[ @ _ intersect length 1 = ] filter ; inline

: sum-and-product ( -- )
    [ s2 [ mul-eq ] [ sum-eq ] [ only-1 ] [email protected] . ] time ;

MAIN: sum-and-product


package main

import "fmt"

type pair struct{ x, y int }

func main() {
	//const max = 100
	// Use 1685 (the highest with a unique answer) instead
	// of 100 just to make it work a little harder :).
	const max = 1685
	var all []pair
	for a := 2; a < max; a++ {
		for b := a + 1; b < max-a; b++ {
			all = append(all, pair{a, b})
		}
	}
	fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)")
	products := countProducts(all)

	// Those for which no sum decomposition has unique product to are
	// S mathimatician's possible pairs.
	var sPairs []pair
pairs:
	for _, p := range all {
		s := p.x + p.y
		// foreach a+b=s (a<b)
		for a := 2; a < s/2+s&1; a++ {
			b := s - a
			if products[a*b] == 1 {
				// Excluded because P would have a unique product
				continue pairs
			}
		}
		sPairs = append(sPairs, p)
	}
	fmt.Println("S starts with", len(sPairs), "possible pairs.")
	//fmt.Println("S pairs:", sPairs)
	sProducts := countProducts(sPairs)

	// Look in sPairs for those with a unique product to get
	// P mathimatician's possible pairs.
	var pPairs []pair
	for _, p := range sPairs {
		if sProducts[p.x*p.y] == 1 {
			pPairs = append(pPairs, p)
		}
	}
	fmt.Println("P then has", len(pPairs), "possible pairs.")
	//fmt.Println("P pairs:", pPairs)
	pSums := countSums(pPairs)

	// Finally, look in pPairs for those with a unique sum
	var final []pair
	for _, p := range pPairs {
		if pSums[p.x+p.y] == 1 {
			final = append(final, p)
		}
	}

	// Nicely show any answers.
	switch len(final) {
	case 1:
		fmt.Println("Answer:", final[0].x, "and", final[0].y)
	case 0:
		fmt.Println("No possible answer.")
	default:
		fmt.Println(len(final), "possible answers:", final)
	}
}

func countProducts(list []pair) map[int]int {
	m := make(map[int]int)
	for _, p := range list {
		m[p.x*p.y]++
	}
	return m
}

func countSums(list []pair) map[int]int {
	m := make(map[int]int)
	for _, p := range list {
		m[p.x+p.y]++
	}
	return m
}

// not used, manually inlined above
func decomposeSum(s int) []pair {
	pairs := make([]pair, 0, s/2)
	for a := 2; a < s/2+s&1; a++ {
		pairs = append(pairs, pair{a, s - a})
	}
	return pairs
}


Define i, sum.d

For i=1 To 1000
  sum+1.0/(i*i)
Next i

Debug sum


print ( sum(1.0 / (x * x) for x in range(1, 1001)) )


( ( sumprod
  =   sum prod num
    .   0:?sum
      & 1:?prod
      & (   !arg
          :   ?
              ( #%?num ?
              & !num+!sum:?sum
              & !num*!prod:?prod
              & ~
              )
        | (!sum.!prod)
        )
  )
& out$sumprod$(2 3 5 7 11 13 17 19)
);


/* using pointer arithmetic (because we can, I guess) */
int arg[] = { 1,2,3,4,5 };
int arg_length = sizeof(arg)/sizeof(arg[0]);
int *end = arg+arg_length;
int sum = 0, prod = 1;
int *p;

for (p = arg; p!=end; ++p) {
   sum += *p;
   prod *= *p;
}


int sum = 0, prod = 1;
int[] arg = { 1, 2, 3, 4, 5 };
foreach (int value in arg) {
  sum += value;
  prod *= value;
}