with javascript_semantics
enum SUB=-1, NOP=0, ADD=1

function evaluate(sequence s)
integer res = 0, tmp = 0, op = ADD
    for i=1 to length(s) do
        if s[i]=NOP then
            tmp = tmp*10+i
        else
            res += op*tmp
            tmp = i
            op = s[i]
        end if
    end for
    return res + op*tmp
end function

procedure show(sequence s)
string res = ""
    for i=1 to length(s) do
        if s[i]!=NOP then
            res &= ','-s[i]
        end if
        res &= '0'+i
    end for
    printf(1,"%s = %d\n",{res,evaluate(s)})
end procedure

-- Logically this intersperses -/nop/+ between each digit, but you do not actually need the digit.
sequence s = repeat(SUB,9)  -- (==> ..nop+add*8)

bool done = false
integer maxl = 0, maxr
integer count = 0
while not done do
    count += 1
    integer r = evaluate(s), k = getd_index(r)
    sequence solns = iff(k=0?{}:deep_copy(getd_by_index(k)))
    solns = append(solns,deep_copy(s))
    setd(r,solns)
    if r>0 and maxl<length(solns) then
        maxl = length(solns)
        maxr = r
    end if
    for i=length(s) to 1 by -1 do
        if i=1 and s[i]=NOP then
            done = true
            exit
        elsif s[i]!=ADD then
            s[i] += 1
            exit
        end if
        s[i] = SUB
    end for
end while

printf(1,"%d solutions considered (dictionary size: %d)\n",{count,dict_size()})

sequence s100 = getd(100)
printf(1,"There are %d sums to 100:\n",{length(s100)})
papply(s100,show)

printf(1,"The positive sum of %d has the maximum number of solutions: %d\n",{maxr,maxl})

integer prev = 0
function missing(integer key, sequence /*data*/, integer /*pkey*/, object /*user_data=-2*/)
    if key!=prev+1 then
        return 0
    end if
    prev = key
    return 1
end function
traverse_dict_partial_key(missing,1)
printf(1,"The lowest positive sum that cannot be expressed: %d\n",{prev+1})

sequence highest = {}
function top10(integer key, sequence /*data*/, object /*user_data*/)
    highest &= key
    return length(highest)<10
end function
--DEV named params on builtins need pre-loading...:
--traverse_dict(top10,rev:=1)
traverse_dict(top10,0,1,true)
printf(1,"The 10 highest sums: %v\n",{highest})


main =>
    L = "23456789",
    gen(L,Str),
    Exp = parse_term(['1'|Str]),
    Exp =:= 100,
    println(['1'|Str]).

gen([email protected][_],Str) => Str = L.
gen([D|Ds],Str) ?=> Str = [D|StrR], gen(Ds,StrR).     % no operator
gen([D|Ds],Str) ?=> Str = ['+',D|StrR], gen(Ds,StrR). % insert +
gen([D|Ds],Str) => Str = ['-',D|StrR], gen(Ds,StrR).  % insert -


#START=6561
#STOPP=19682
#SUMME=100
#BASIS="123456789"

Structure TSumTerm
  sum.i
  ter.s
EndStructure

NewList Solutions.TSumTerm()
NewMap SolCount.i()
Dim op.s{1}(8)
Dim b.s{1}(8)
PokeS(@b(),#BASIS)

Procedure StripTerm(*p_Term)
  If PeekS(*p_Term,1)="+" : PokeC(*p_Term,' ') : EndIf
EndProcedure

Procedure.s Triadisch(v)
  While v : r$=Str(v%3)+r$ : v/3 : Wend
  ProcedureReturn r$
EndProcedure

Procedure.i Calc(t$)
  While Len(t$)
    x=Val(t$) : r+x
    If x<0 : s$=Str(x) : Else : s$="+"+Str(x) : EndIf
    t$=RemoveString(t$,s$,#PB_String_NoCase,1,1)
  Wend
  ProcedureReturn r
EndProcedure

For n=#START To #STOPP
  PokeS(@op(),Triadisch(n))
  Term$=""
  For i=0 To 8
    Select op(i)
      Case "0" : Term$+    b(i)
      Case "1" : Term$+"+"+b(i)
      Case "2" : Term$+"-"+b(i)
    EndSelect
  Next
  AddElement(Solutions()) : Solutions()\sum=Calc(Term$) : StripTerm(@Term$) : Solutions()\ter=Term$
Next
SortStructuredList(Solutions(),#PB_Sort_Ascending,OffsetOf(TSumTerm\sum),TypeOf(TSumTerm\sum))

If OpenConsole()
  PrintN("Show all solutions that sum to 100:")
  ForEach Solutions()
    If Solutions()\sum=#SUMME : PrintN(#TAB$+Solutions()\ter) : EndIf
    SolCount(Str(Solutions()\sum))+1
  Next
  ForEach SolCount()
    If SolCount()>MaxCount : MaxCount=SolCount() : MaxVal$=MapKey(SolCount()) : EndIf
  Next
  PrintN("Show the positve sum that has the maximum number of solutions:")
  PrintN(#TAB$+MaxVal$+" has "+Str(MaxCount)+" solutions")
  If LastElement(Solutions())
    MaxVal=Solutions()\sum
    PrintN("Show the lowest positive number that can't be expressed:")
    For i=1 To MaxVal
      If SolCount(Str(i))=0 : PrintN(#TAB$+Str(i)) : Break : EndIf
    Next
    PrintN("Show the 10 highest numbers that can be expressed:")
    For i=1 To 10
      PrintN(#TAB$+LSet(Str(Solutions()\sum),9)+" = "+Solutions()\ter)
      If Not PreviousElement(Solutions()) : Break : EndIf
    Next
  EndIf
  Input()
EndIf


from itertools import product, islice

def expr(p):
    return "{}1{}2{}3{}4{}5{}6{}7{}8{}9".format(*p)

def gen_expr():
    op = ['+', '-', '']
    return [expr(p) for p in product(op, repeat=9) if p[0] != '+']

def all_exprs():
    values = {}
    for expr in gen_expr():
        val = eval(expr)
        if val not in values:
            values[val] = 1
        else:
            values[val] += 1
    return values

def sum_to(val):
    for s in filter(lambda x: x[0] == val, map(lambda x: (eval(x), x), gen_expr())):
        print(s)

def max_solve():
    print("Sum {} has the maximum number of solutions: {}".
          format(*max(all_exprs().items(), key=lambda x: x[1])))

def min_solve():
    values = all_exprs()
    for i in range(123456789):
        if i not in values:
            print("Lowest positive sum that can't be expressed: {}".format(i))
            return

def highest_sums(n=10):
    sums = map(lambda x: x[0],
               islice(sorted(all_exprs().items(), key=lambda x: x[0], reverse=True), n))
    print("Highest Sums: {}".format(list(sums)))

sum_to(100)
max_solve()
min_solve()
highest_sums()


#lang racket

(define list-partitions
  (match-lambda
    [(list) (list null)]
    [(and L (list _)) (list (list L))]
    [(list L ...)
     (for*/list
          ((i (in-range 1 (add1 (length L))))
           (r (in-list (list-partitions (drop L i)))))
        (cons (take L i) r))]))

(define digits->number (curry foldl (λ (dgt acc) (+ (* 10 acc) dgt)) 0))

(define partition-digits-to-numbers
  (let ((memo (make-hash)))
    (λ (dgts)
      (hash-ref! memo dgts
                 (λ ()
                   (map (λ (p) (map digits->number p))
                        (list-partitions dgts)))))))

(define (fold-sum-to-ns digits kons k0)
  (define (get-solutions nmbrs acc chain k)
    (match nmbrs
      [(list)
       (kons (cons acc (let ((niahc (reverse chain)))
                         (if (eq? '+ (car niahc)) (cdr niahc) niahc)))
             k)]
      [(cons a d)
       (get-solutions d (- acc a) (list* a '- chain)
                      (get-solutions d (+ acc a) (list* a '+ chain) k))]))
  (foldl (λ (nmbrs k) (get-solutions nmbrs 0 null k)) k0 (partition-digits-to-numbers digits)))

(define sum-to-ns/hash-promise
  (delay (fold-sum-to-ns
          '(1 2 3 4 5 6 7 8 9)
          (λ (a.s d) (hash-update d (car a.s) (λ (x) (cons (cdr a.s) x)) list))
          (hash))))

(module+ main
  (define S (force sum-to-ns/hash-promise))
  (displayln "Show all solutions that sum to 100")
  (pretty-print (hash-ref S 100))

  (displayln "Show the sum that has the maximum number of solutions (from zero to infinity*)")
  (let-values (([k-max v-max]
                (for/fold ((k-max #f) (v-max 0))
                          (([k v] (in-hash S)) #:when (> (length v) v-max))
                  (values k (length v)))))
    (printf "~a has ~a solutions~%" k-max v-max))

  (displayln "Show the lowest positive sum that can't be expressed (has no solutions),
 using the rules for this task")
  (for/first ((n (in-range 1 (add1 123456789))) #:unless (hash-has-key? S n)) n)

  (displayln "Show the ten highest numbers that can be expressed using the rules for this task")
  (take (sort (hash-keys S) >) 10))

(module+ test
  (require rackunit)
  (check-equal? (list-partitions null) '(()))
  (check-equal? (list-partitions '(1)) '(((1))))
  (check-equal? (list-partitions '(1 2)) '(((1) (2)) ((1 2))))
  (check-equal? (partition-digits-to-numbers '()) '(()))
  (check-equal? (partition-digits-to-numbers '(1)) '((1)))
  (check-equal? (partition-digits-to-numbers '(1 2)) '((1 2) (12))))


my $sum = 100;
my $N   = 10;
my @ops = ['-', ''], |( [' + ', ' - ', ''] xx 8 );
my @str = [X~] map { .Slip }, ( @ops Z 1..9 );
my %sol = @str.classify: *.subst( ' - ', ' -', :g )\
                          .subst( ' + ',  ' ', :g ).words.sum;

my %count.push: %sol.map({ .value.elems => .key });

my $max-solutions    = %count.max( + *.key );
my $first-unsolvable = first { %sol{$_} :!exists }, 1..*;
sub n-largest-sums (Int $n) { %sol.sort(-*.key)[^$n].fmt: "%8s => %s\n" }

given %sol{$sum}:p {
    say "{.value.elems} solutions for sum {.key}:";
    say "    $_" for .value.list;
}

.say for :$max-solutions, :$first-unsolvable, "$N largest sums:", n-largest-sums($N);


/*REXX pgm solves a puzzle:  using the string 123456789, insert  -  or  +  to sum to 100*/
parse arg LO HI .                                /*obtain optional arguments from the CL*/
if LO=='' | LO==","  then LO=       100          /*Not specified?  Then use the default.*/
if HI=='' | HI==","  then HI=        LO          /* "      "         "   "   "     "    */
if LO==00            then HI= 123456789          /*LOW specified as zero with leading 0.*/
ops= '+-';             L= length(ops) + 1        /*define operators (and their length). */
@.=;      do i=1  for L-1;  @.i= substr(ops,i,1) /*   "   some handy-dandy REXX literals*/
          end   /*i*/                            /*   "   individual operators for speed*/
mx= 0;  mn= 999999                               /*initialize the minimums and maximums.*/
mxL=;   mnL=;         do j=LO  to HI  until LO==00  &  mn==0  /*solve with range of sums*/
                      z= ???(j)                               /*find # solutions for J. */
                      if z> mx  then     mxL=                 /*is this a new maximum ? */
                      if z>=mx  then do; mxL=mxL j; mx=z; end /*remember this new max.  */
                      if z< mn  then     mnL=                 /*is this a new minimum ? */
                      if z<=mn  then do; mnL=mnL j; mn=z; end /*remember this new min.  */
                      end   /*j*/
if LO==HI  then exit 0                                        /*don't display max&min ? */
@@= 'number of solutions: ';   say
_= words(mxL);  say 'sum's(_)   "of"   mxL  ' 's(_,"have",'has')   'the maximum'   @@   mx
_= words(mnL);  say 'sum's(_)   "of"   mnL  ' 's(_,"have",'has')   'the minimum'   @@   mn
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s:   if arg(1)==1  then return arg(3);   return word( arg(2) "s",1)  /*simple pluralizer*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
???: parse arg answer;          #= 0             /*obtain the answer (sum) to the puzzle*/
       do         a=L-1  for 2; aa=       @.a'1' /*choose one  of  -       or  nothing. */
        do        b=1  for L;   bb= aa || @.b'2' /*   "    "    "  -   +,  or  abutment.*/
         do       c=1  for L;   cc= bb || @.c'3' /*   "    "    "  "   "    "      "    */
          do      d=1  for L;   dd= cc || @.d'4' /*   "    "    "  "   "    "      "    */
           do     e=1  for L;   ee= dd || @.e'5' /*   "    "    "  "   "    "      "    */
            do    f=1  for L;   ff= ee || @.f'6' /*   "    "    "  "   "    "      "    */
             do   g=1  for L;   gg= ff || @.g'7' /*   "    "    "  "   "    "      "    */
              do  h=1  for L;   hh= gg || @.h'8' /*   "    "    "  "   "    "      "    */
               do i=1  for L;   ii= hh || @.i'9' /*   "    "    "  "   "    "      "    */
               interpret '$='   ii               /*calculate the sum of modified string.*/
               if $\==answer  then iterate       /*Is sum not equal to answer? Then skip*/
               #= # + 1;        if LO==HI  then say 'solution: '    $    " ◄───► "    ii
               end   /*i*/                       /*                                     */
              end    /*h*/                       /*                          d          */
             end     /*g*/                       /*                          d          */
            end      /*f*/                       /*   eeeee   n nnnn    dddddd   sssss  */
           end       /*e*/                       /*  e     e  nn    n  d     d  s       */
          end        /*d*/                       /*  eeeeeee  n     n  d     d   sssss  */
         end         /*c*/                       /*  e        n     n  d     d        s */
        end          /*b*/                       /*   eeeee   n     n   ddddd    sssss  */
       end           /*a*/                       /*                                     */
     y= #                                        /* [↓]  adjust the number of solutions?*/
     if y==0  then y= 'no'                       /* [↓]  left justify plural of solution*/
     if LO\==00  then say right(y, 9)          'solution's(#, , " ")     'found for'  ,
                          right(j, length(HI) )                           left('', #, "─")
     return #                                    /*return the number of solutions found.*/


digits = ("1".."9").to_a

ar = ["+", "-", ""].repeated_permutation(digits.size).filter_map do |op_perm|
  str = op_perm.zip(digits).join
  str unless str.start_with?("+")
end
res = ar.group_by{|str| eval(str)}

puts res[100] , ""

sum, solutions = res.max_by{|k,v| v.size}
puts "#{sum} has #{solutions.size} solutions.", ""

no_solution = (1..).find{|n| res[n] == nil}
puts "#{no_solution} is the lowest positive number without a solution.", ""

puts res.max(10).map{|pair| pair.join(": ")}


object SumTo100 {
  def main(args: Array[String]): Unit = {
    val exps = expressions(9).map(str => (str, eval(str)))
    val sums = exps.map(_._2).sortWith(_>_)

    val s1 = exps.filter(_._2 == 100)
    val s2 = sums.distinct.map(s => (s, sums.count(_ == s))).maxBy(_._2)
    val s3 = sums.distinct.reverse.filter(_>0).zipWithIndex.dropWhile{case (n, i) => n == i + 1}.head._2 + 1
    val s4 = sums.distinct.take(10)

    println(s"""All ${s1.size} solutions that sum to 100:
               |${s1.sortBy(_._1.length).map(p => s"${p._2} = ${p._1.tail}").mkString("\n")}
               |
               |Most common sum: ${s2._1} (${s2._2})
               |Lowest unreachable sum: $s3
               |Highest 10 sums: ${s4.mkString(", ")}""".stripMargin)
  }

  def expressions(l: Int): LazyList[String] = configurations(l).map(p => p.zipWithIndex.map{case (op, n) => s"${opChar(op)}${n + 1}"}.mkString)
  def configurations(l: Int): LazyList[Vector[Int]] = LazyList.range(0, math.pow(3, l).toInt).map(config(l)).filter(_.head != 0)
  def config(l: Int)(num: Int): Vector[Int] = Iterator.iterate((num%3, num/3)){case (_, n) => (n%3, n/3)}.map(_._1 - 1).take(l).toVector

  def eval(exp: String): Int = (exp.headOption, exp.tail.takeWhile(_.isDigit), exp.tail.dropWhile(_.isDigit)) match{
    case (Some(op), n, str) => doOp(op, n.toInt) + eval(str)
    case _ => 0
  }

  def doOp(sel: Char, n: Int): Int = if(sel == '-') -n else n
  def opChar(sel: Int): String = sel match{
    case -1 => "-"
    case 1 => "+"
    case _ => ""
  }
}


func gen_expr() is cached {
    var x = ['-', '']
    var y = ['+', '-', '']

    gather {
        cartesian([x,y,y,y,y,y,y,y,y], {|a,b,c,d,e,f,g,h,i|
            take("#{a}1#{b}2#{c}3#{d}4#{e}5#{f}6#{g}7#{h}8#{i}9")
        })
    }
}

func eval_expr(expr) is cached {
    expr.scan(/([-+]?\d+)/).sum_by { Num(_) }
}

func sum_to(val) {
    gen_expr().grep { eval_expr(_) == val }
}

func max_solve() {
    gen_expr().grep     { eval_expr(_) >= 0 } \
              .group_by { eval_expr(_)      } \
              .max_by   {|_,v| v.len        }
}

func min_solve() {
    var h = gen_expr().group_by { eval_expr(_) }
    for i in (0..Inf) { h.exists(i) || return i }
}

func highest_sums(n=10) {
    gen_expr().map { eval_expr(_) }.uniq.sort.reverse.first(n)
}

sum_to(100).each { say "100 = #{_}" }

var (n, solutions) = max_solve()...
say "Sum of #{n} has the maximum number of solutions: #{solutions.len}"
say "Lowest positive sum that can't be expressed : #{min_solve()}"
say "Highest sums: #{highest_sums()}"


proc sum_to_100 {} {
    for {set i 0} {$i <= 13121} {incr i} {
	set i3 [format %09d [dec2base 3 $i]]
	set form ""
	set subs {"" - +}
	foreach a [split $i3 ""] b [split 123456789 ""] {
	    append form [lindex $subs $a] $b
	}
	lappend R([expr $form]) $form
    }
    puts "solutions for sum=100:\n[join [lsort $R(100)] \n]"
    set max -1
    foreach key [array names R] {
	if {[llength $R($key)] > $max} {
	    set max [llength $R($key)]
	    set maxkey $key
	}
    }
    puts "max solutions: $max for $maxkey"
    for {set i 0} {$i <= 123456789} {incr i} {
	if ![info exists R($i)] {
	    puts "first unsolvable: $i"
	    break
	}
    }
    puts "highest 10:\n[lrange [lsort -integer -decr [array names R]] 0 9]"
}
proc dec2base {base dec} {
    set res ""
    while {$dec > 0} {
	set res [expr $dec%$base]$res
	set dec [expr $dec/$base]
    }
    if {$res eq ""} {set res 0}
    return $res
}
sum_to_100


' Recursively iterates (increments) iteration array, returns -1 when out of "digits".
Function plusOne(iAry() As Integer, spot As Integer) As Integer
    Dim spotLim As Integer = If(spot = 0, 1, 2) ' The first "digit" has a lower limit.
    If iAry(spot) = spotLim Then ' Check if spot has reached limit
        If spot = 0 Then Return -1 ' No previous spot to increment, so indicate completed.
        iAry(spot) = 0 ' Reset current spot, and
        Return plusOne(iAry, spot - 1) ' Increment previous spot.
    Else
        iAry(spot) += 1 ' Increment current spot.
    End If
    Return spot
End Function

' Returns string sequence of operations from iAry and terms string
Function generate(iAry() As Integer, terms As String) As String
    Dim operations As String() = {"", "-", "+"} ' Possible operations.
    generate = ""
    For i As Integer = 0 To iAry.Count - 1
        generate &= operations(iAry(i)) & Mid(terms, i + 1, 1).ToString()
    Next
End Function

' Returns evaluation of string sequence
Function eval(sequence As String) As Integer
    eval = 0
    Dim term As Integer = 0, operation As Integer = 1
    For Each ch As Char In sequence
        Select Case ch
            Case "-", "+" ' New operation detected, apply previous operation to term,
                eval += If(operation = 0, -term, term) : term = 0 ' and reset term.
                operation = If(ch = "-", 0, 1) ' Note next operation.
            Case Else ' Digit detected, increase term.
                term = term * 10 + Val(ch)
        End Select
    Next
    eval += If(operation = 0, -term, term) ' Apply final term.
End Function

' Sorts a pair of List(Of Integer) by the first
Sub reSort(ByRef first As List(Of Integer), ByRef second As List(Of Integer))
    Dim lou As New List(Of ULong) ' Temporary list of ULong for sorting.
    For i As Integer = 0 To first.Count - 1
        lou.Add((CULng(first(i)) << 32) + second(i)) ' "Pack" list items.
    Next
    lou.Sort()
    For k As Integer = 0 To first.Count - 1
        first(k) = lou(k) >> 32 ' "Unpack" first list item.
        second(k) = lou(k) And &H7FFFFFFF ' "Unpack" second list item.
    Next
End Sub

' Returns first result not in sequence, assumes passed list is sorted before call,
'  uses binary search algo.
Function firstMiss(loi As List(Of Integer))
    Dim low As Integer = 0, high As Integer = loi.Count - 1, middle = (low + high) \ 2
    Do
        If loi(middle) = middle Then low = middle + 1 Else high = middle - 1
        middle = (low + high) \ 2
    Loop Until high <= low
    Return middle + If(loi(middle) = middle, 1, 0)
End Function

' Iterates through all possible operations,
'  uses a pair of List (of Integer) to tabulate solutions.
Sub Solve100(Optional terms As String = "123456789",
             Optional targSum As Integer = 100,
             Optional highNums As Integer = 10)
    Dim lastDig As Integer = Len(terms) - 1 ' The final "digit".
    Dim iAry() As Integer = New Integer(lastDig) {} ' Iterations array.
    Dim seq As String ' Sequence of numbers and operations.
    Dim sVal As Integer ' Sequence value.
    Dim sCnt As Integer = 1 ' Solution count (targSum).
    Dim res As New List(Of Integer) ' List of results.
    Dim tally As New List(Of Integer) ' Tally of results.
    Console.WriteLine("List of solutions that evaluate to 100:")
    Do ' Tabulate results until digits are exhausted.
        seq = generate(iAry, terms) ' Obtain next expression.
        sVal = eval(seq) ' Obtain next evaluation.
        If sVal >= 0 Then ' Don't bother saving the negative results.
            If res.Contains(sVal) Then tally(res.IndexOf(sVal)) += 1 _
                                  Else res.Add(sVal) : tally.Add(1)
            If sVal = targSum Then _
                Console.WriteLine(" {0,2} {1}", sCnt, seq) : sCnt += 1
        End If
    Loop Until plusOne(iAry, lastDig) < 0
    reSort(tally, res) ' Sort by tally to find result with the most solutions.
    Console.WriteLine("The sum that has the the most solutions is {0}, (at {1}).",
                      res.Last, tally.Last)
    reSort(res, tally) ' Sort by result to find first missing result and top results.
    Console.WriteLine("The lowest positive sum that can't be expressed is {0}.",
                      firstMiss(res))
    Console.WriteLine("The ten highest numbers that can be expressed are:")
    res.Reverse() ' To let us take the last items for output.
    sCnt = 0 ' Keep track of items displayed (for formatting).
    For Each item As Integer In res.Take(highNums)
        Console.Write("{0, -11}", item)
        sCnt = (sCnt + 1) Mod 5 : If sCnt = 0 Then Console.WriteLine()
    Next
End Sub

Sub Main()
    Solve100() ' if interested, try this: Solve100("987654321")
End Sub


import "/dynamic" for Enum
import "/fmt" for Fmt
import "/set" for Set
import "/math" for Nums
import "/sort" for Sort

var Op = Enum.create("Op", ["ADD", "SUB", "JOIN"])

var NUMBER_OF_DIGITS = 9
var THREE_POW_4 = 3 * 3 * 3 * 3
var NUMBER_OF_EXPRESSIONS = 2 * THREE_POW_4 * THREE_POW_4

class Expression {
    static print(givenSum) {
        var expr = Expression.new()
        for (i in 0...NUMBER_OF_EXPRESSIONS) {
            if (expr.toInt == givenSum) Fmt.print("$9d = $s", givenSum, expr)
            expr.inc
        }
    }

    construct new() {
        _code = List.filled(NUMBER_OF_DIGITS, Op.ADD)
    }

    inc {
        for (i in 0..._code.count) {
            _code[i] = (_code[i] == Op.ADD) ? Op.SUB : (_code[i] == Op.SUB) ? Op.JOIN : Op.ADD
            if (_code[i] != Op.ADD) break
        }
        return this
    }

    toInt {
        var value = 0
        var number = 0
        var sign = 1
        for (digit in 1..9) {
            var c = _code[NUMBER_OF_DIGITS - digit]
            if (c == Op.ADD) {
                value = value + sign * number
                number = digit
                sign = 1
            } else if (c == Op.SUB) {
                value = value + sign * number
                number = digit
                sign = -1
            } else {
                number = 10 * number + digit
            }
        }
        return value + sign * number
    }

    toString {
        var sb = ""
        for (digit in 1..NUMBER_OF_DIGITS) {
            var c = _code[NUMBER_OF_DIGITS - digit]
            if (c == Op.ADD) {
                if (digit > 1) sb = sb + " + "
            } else if (c == Op.SUB) {
                sb = sb + " - "
            }
            sb = sb + digit.toString
        }
        return sb.trimStart()
    }
}

class Stat {
    construct new() {
        _countSum = {}
        _sumCount = {}
        var expr = Expression.new()
        for (i in 0...NUMBER_OF_EXPRESSIONS) {
            var sum = expr.toInt
            _countSum[sum] = _countSum[sum] ? 1 + _countSum[sum] : 1
            expr.inc
        }
        for (me in _countSum) {
            var set = _sumCount.containsKey(me.value) ? _sumCount[me.value] : Set.new()
            set.add(me.key)
            _sumCount[me.value] = set
        }
    }

    countSum { _countSum }
    sumCount { _sumCount }
}

System.print("100 has the following solutions:\n")
Expression.print(100)

var stat = Stat.new()
var maxCount = Nums.max(stat.sumCount.keys)
var maxSum = Nums.max(stat.sumCount[maxCount])
System.print("\n%(maxSum) has the maximum number of solutions, namely %(maxCount)")

var value = 0
while (stat.countSum.containsKey(value)) value = value + 1
System.print("\n%(value) is the lowest positive number with no solutions")

System.print("\nThe ten highest numbers that do have solutions are:\n")
var res = stat.countSum.keys.toList
Sort.quick(res)
res[-1..0].take(10).each { |e| Expression.print(e) }


F sum_digits(=n, base)
   V r = 0
   L n > 0
      r += n % base
      n I/= base
   R r

print(sum_digits(1, 10))
print(sum_digits(1234, 10))
print(sum_digits(F'E, 16))
print(sum_digits(0F'0E, 16))


*        Sum digits of an integer  08/07/2016
SUMDIGIN CSECT
         USING  SUMDIGIN,R13       base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    prolog
         ST     R13,4(R15)         " <-
         ST     R15,8(R13)         " ->
         LR     R13,R15            " addressability
         LA     R11,NUMBERS        @numbers
         LA     R8,1               k=1
LOOPK    CH     R8,=H'4'           do k=1 to hbound(numbers)
         BH     ELOOPK             "
         SR     R10,R10              sum=0
         LA     R7,1                 j=1
LOOPJ    CH     R7,=H'8'             do j=1 to length(number)
         BH     ELOOPJ               "
         LR     R4,R11                 @number
         BCTR   R4,0                   -1
         AR     R4,R7                  +j
         MVC    D,0(R4)                d=substr(number,j,1)
         SR     R9,R9                  ii=0
         SR     R6,R6                  i=0
LOOPI    CH     R6,=H'15'              do i=0 to 15
         BH     ELOOPI                 "
         LA     R4,DIGITS                @digits
         AR     R4,R6                    i
         MVC    C,0(R4)                  c=substr(digits,i+1,1)
         CLC    D,C                      if d=c
         BNE    NOTEQ                    then
         LR     R9,R6                      ii=i
         B      ELOOPI                     leave i
NOTEQ    LA     R6,1(R6)                 i=i+1
         B      LOOPI                  end do i
ELOOPI   AR     R10,R9                 sum=sum+ii
         LA     R7,1(R7)               j=j+1
         B      LOOPJ                end do j
ELOOPJ   MVC    PG(8),0(R11)         number
         XDECO  R10,XDEC             edit sum
         MVC    PG+8(8),XDEC+4       output sum
         XPRNT  PG,L'PG              print buffer
         LA     R11,8(R11)           @[email protected]+8
         LA     R8,1(R8)             k=k+1
         B      LOOPK              end do k
ELOOPK   L      R13,4(0,R13)       epilog
         LM     R14,R12,12(R13)    " restore
         XR     R15,R15            " rc=0
         BR     R14                exit
DIGITS   DC     CL16'0123456789ABCDEF'
NUMBERS  DC     CL8'1',CL8'1234',CL8'FE',CL8'F0E'
C        DS     CL1
D        DS     CL1
PG       DC     CL16' '            buffer
XDEC     DS     CL12               temp
         YREGS
         END    SUMDIGIN


	cpu	8086
	org	100h
section	.text
	jmp	demo
	;;;	Sum of digits of AX in base BX.
	;;;	Returns: AX = result
	;;;	CX, DX destroyed.
digsum:	xor	cx,cx		; Result
.loop:	xor	dx,dx		; Divide AX by BX
	div	bx		; Quotient in AX, modulus in DX
	add	cx,dx		; Add digit to sum
	test	ax,ax		; Is the quotient now zero?
	jnz	.loop		; If not, keep going
	mov	ax,cx		; Otherwise, return
	ret
	;;;	Print the value of AX in decimal using DOS.
	;;;	(Note the similarity.)
pr_ax:	mov	bx,num		; Number buffer pointer
	mov	cx,10		; Divisor
.loop:	xor	dx,dx		; Get digit
	div	cx
	add	dl,'0'		; Make ASCII digit
	dec	bx		; Store in buffer
	mov	[bx],dl
	test	ax,ax		; More digits?
	jnz	.loop		; If so, keep going
	mov	dx,bx		; Begin of number in DX
	mov	ah,9		; MS-DOS syscall 9 prints $-terminated string
	int	21h
	ret
	;;;	Run the function on the given examples
demo:	mov	si,tests	; Pointer to example array
.loop:	lodsw			; Get base
	test	ax,ax		; If 0, we're done
	jz	.done
	xchg	bx,ax
	lodsw			; Get number
	call	digsum		; Calculate sum of digits
	call	pr_ax		; Print sum of digits
	jmp	.loop		; Get next pair
.done:	ret
section	.data
	db	'*****'		; Placeholder for numeric output
num:	db	13,10,'$'
tests:	dw	10, 1		; Examples
	dw	10, 1234
	dw	16, 0FEh
	dw	16, 0F0Eh
	dw	0		; End marker


CARD FUNC SumDigits(CARD num,base)
  CARD res,a

  res=0
  WHILE num#0
  DO
    res==+num MOD base
    num=num/base
  OD
RETURN(res)

PROC Main()
  CARD ARRAY data=[
      1 10  1234 10  $FE 16  $F0E 16
      $FF 2  0 2  2186 3  2187 3]
  BYTE i
  CARD num,base,res

  FOR i=0 TO 15 STEP 2
  DO
    num=data(i)
    base=data(i+1)
    res=SumDigits(num,base)
    PrintF("num=%U base=%U sum=%U%E",num,base,res)
  OD
RETURN


with Ada.Integer_Text_IO;

procedure Sum_Digits is
   -- sums the digits of an integer (in whatever base)
   -- outputs the sum (in base 10)

   function Sum_Of_Digits(N: Natural; Base: Natural := 10) return Natural is
      Sum: Natural := 0;
      Val: Natural := N;
   begin
      while Val > 0 loop
         Sum := Sum + (Val mod Base);
         Val := Val / Base;
      end loop;
      return Sum;
   end Sum_Of_Digits;

   use Ada.Integer_Text_IO;

begin -- main procedure Sum_Digits
   Put(Sum_OF_Digits(1));            --   1
   Put(Sum_OF_Digits(12345));        --  15
   Put(Sum_OF_Digits(123045));       --  15
   Put(Sum_OF_Digits(123045,  50));  -- 104
   Put(Sum_OF_Digits(16#fe#,  10));  --  11
   Put(Sum_OF_Digits(16#fe#,  16));  --  29
   Put(Sum_OF_Digits(16#f0e#, 16));  --  29
end Sum_Digits;


# operator to return the sum of the digits of an integer value in the #
# specified base                                                      #
PRIO SUMDIGITS = 1;
OP   SUMDIGITS = ( INT value, INT base )INT:
     IF base < 2
     THEN
         # invalid base #
         print( ( "Base for digit sum must be at least 2", newline ) );
         stop
     ELSE
         # the base is OK #
         INT    result := 0;
         INT    rest   := ABS value;

         WHILE rest /= 0
         DO
             result PLUSAB ( rest MOD base );
             rest   OVERAB base
         OD;

         result
     FI; # SUMDIGITS #

# additional operator so we can sum the digits of values expressed in #
# other than base 10, e.g. 16ra is a hex lteral with value 10         #
# (Algol 68 allows bases 2, 4, 8 and 16 for non-base 10 literals)     #
# however as such literals are BITS values, not INTs, we need this    #
# second operator                                                     #
OP   SUMDIGITS = ( BITS value, INT base )INT: ABS value SUMDIGITS base;

main:(

    # test the SUMDIGITS operator #

    print( ( "value\base base digit-sum", newline ) );
    print( ( "      1\10   10 ", whole(      1 SUMDIGITS 10, -9 ), newline ) );
    print( ( "   1234\10   10 ", whole(   1234 SUMDIGITS 10, -9 ), newline ) );
    print( ( "     fe\16   16 ", whole(  16rfe SUMDIGITS 16, -9 ), newline ) );
    print( ( "    f0e\16   16 ", whole( 16rf0e SUMDIGITS 16, -9 ), newline ) );

    # of course, we don't have to express the number in the base we sum #
    # the digits in...                                                  #
    print( ( "     73\10   71 ", whole(     73 SUMDIGITS 71, -9 ), newline ) )

)


----------------- SUM DIGITS OF AN INTEGER -----------------

-- baseDigitSum :: Int -> Int -> Int
on baseDigitSum(base)
    script
        on |λ|(n)
            script go
                on |λ|(x)
                    if 0 < x then
                        Just({x mod base, x div base})
                    else
                        Nothing()
                    end if
                end |λ|
            end script
            sum(unfoldl(go, n))
        end |λ|
    end script
end baseDigitSum

--------------------------- TEST ---------------------------
on run
    {ap(map(baseDigitSum, {2, 8, 10, 16}), {255}), ¬
        ap(map(baseDigitSum, {10}), {1, 1234}), ¬
        ap(map(baseDigitSum, {16}), map(readHex, {"0xfe", "0xf0e"}))}

    --> {{8, 17, 12, 30}, {1, 10}, {29, 29}}
end run

-------------------- GENERIC FUNCTIONS ---------------------

-- Just :: a -> Maybe a
on Just(x)
    -- Constructor for an inhabited Maybe (option type) value.
    -- Wrapper containing the result of a computation.
    {type:"Maybe", Nothing:false, Just:x}
end Just

-- Nothing :: Maybe a
on Nothing()
    -- Constructor for an empty Maybe (option type) value.
    -- Empty wrapper returned where a computation is not possible.
    {type:"Maybe", Nothing:true}
end Nothing

-- Each member of a list of functions applied to
-- each of a list of arguments, deriving a list of new values
-- ap (<*>) :: [(a -> b)] -> [a] -> [b]
on ap(fs, xs)
    set lst to {}
    repeat with f in fs
        tell mReturn(contents of f)
            repeat with x in xs
                set end of lst to |λ|(contents of x)
            end repeat
        end tell
    end repeat
    return lst
end ap

-- elemIndex :: Eq a => a -> [a] -> Maybe Int
on elemIndex(x, xs)
    set lng to length of xs
    repeat with i from 1 to lng
        if x = (item i of xs) then return Just(i - 1)
    end repeat
    return Nothing()
end elemIndex

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- foldr :: (a -> b -> b) -> b -> [a] -> b
on foldr(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from lng to 1 by -1
            set v to |λ|(item i of xs, v, i, xs)
        end repeat
        return v
    end tell
end foldr

-- identity :: a -> a
on identity(x)
    -- The argument unchanged.
    x
end identity

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    -- The list obtained by applying f
    -- to each element of xs.
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- maybe :: b -> (a -> b) -> Maybe a -> b
on maybe(v, f, mb)
    -- Either the default value v (if mb is Nothing),
    -- or the application of the function f to the
    -- contents of the Just value in mb.
    if Nothing of mb then
        v
    else
        tell mReturn(f) to |λ|(Just of mb)
    end if
end maybe

-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    -- 2nd class handler function lifted into 1st class script wrapper.
    if script is class of f then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- readHex :: String -> Int
on readHex(s)
    -- The integer value of the given hexadecimal string.
    set ds to "0123456789ABCDEF"
    script go
        on |λ|(c, a)
            set {v, e} to a
            set i to maybe(0, my identity, elemIndex(c, ds))
            {v + (i * e), 16 * e}
        end |λ|
    end script
    item 1 of foldr(go, {0, 1}, characters of s)
end readHex

-- sum :: [Num] -> Num
on sum(xs)
    script add
        on |λ|(a, b)
            a + b
        end |λ|
    end script

    foldl(add, 0, xs)
end sum

-- > unfoldl (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
-- > [1,2,3,4,5,6,7,8,9,10]
-- unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
on unfoldl(f, v)
    set xr to {v, v} -- (value, remainder)
    set xs to {}
    tell mReturn(f)
        repeat -- Function applied to remainder.
            set mb to |λ|(item 2 of xr)
            if Nothing of mb then
                exit repeat
            else -- New (value, remainder) tuple,
                set xr to Just of mb
                -- and value appended to output list.
                set xs to ({item 1 of xr} & xs)
            end if
        end repeat
    end tell
    return xs
end unfoldl


F suffize(numstr, digits = -1, base = 10)
   V suffixes = [‘’, ‘K’, ‘M’, ‘G’, ‘T’, ‘P’, ‘E’, ‘Z’, ‘Y’, ‘X’, ‘W’, ‘V’, ‘U’, ‘googol’]

   V exponent_distance = I base == 2 {10} E 3
   V num_sign = I numstr[0] C ‘+-’ {numstr[0]} E ‘’

   V num = abs(Float(numstr.replace(‘,’, ‘’)))

   Int suffix_index
   I base == 10 & num >= 1e100
      suffix_index = 13
      num /= 1e100
   E I num > 1
      V magnitude = floor(log(num, base))
      suffix_index = min(Int(floor(magnitude / exponent_distance)), 12)
      num /= Float(base) ^ (exponent_distance * suffix_index)
   E
      suffix_index = 0

   String num_str
   I digits != -1
      num_str = format_float(num, digits)
   E
      num_str = format_float(num, 3).rtrim(‘0’).rtrim(‘.’)

   R num_sign‘’num_str‘’suffixes[suffix_index]‘’(I base == 2 {‘i’} E ‘’)

F p(num, digits = -1, base = 10)
   print(num, end' ‘ ’)
   I digits != -1
      print(digits, end' ‘ ’)
   I base != 10
      print(‘base = ’base, end' ‘ ’)
   print(‘: ’suffize(num, digits, base))

p(‘87,654,321’)
p(‘-998,877,665,544,332,211,000’, 3)
p(‘+112,233’, 0)
p(‘16,777,216’, 1)
p(‘456,789,100,000,000’, 2)
p(‘456,789,100,000,000’, 5, 2)
p(‘456,789,100,000.000e+00’, 0, 10)
p(‘+16777216’, -1, 2)
p(‘1.2e101’)


LISTEN TO ME VERY CAREFULLY sumDigits
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE base
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE sum
YOU SET US UP @I LIED
STICK AROUND n
HEY CHRISTMAS TREE digit
YOU SET US UP @I LIED
GET TO THE CHOPPER digit
HERE IS MY INVITATION n
I LET HIM GO base
ENOUGH TALK
GET TO THE CHOPPER sum
HERE IS MY INVITATION sum
GET UP digit
ENOUGH TALK
GET TO THE CHOPPER n
HERE IS MY INVITATION n
HE HAD TO SPLIT base
ENOUGH TALK
CHILL
I'LL BE BACK sum
HASTA LA VISTA, BABY

IT'S SHOWTIME
HEY CHRISTMAS TREE sum
YOU SET US UP @I LIED
GET YOUR A** TO MARS sum
DO IT NOW sumDigits 12345 10
TALK TO THE HAND "sumDigits 12345 10 ="
TALK TO THE HAND sum
GET YOUR A** TO MARS sum
DO IT NOW sumDigits 254 16
TALK TO THE HAND "sumDigits 254 16 ="
TALK TO THE HAND sum
YOU HAVE BEEN TERMINATED


sumDigits: function [n base][
	result: 0
	while [n>0][
		result: result + n%base
		n: n/base
    ]
	return result
]

print sumDigits 1 10
print sumDigits 12345 10
print sumDigits 123045 10
print sumDigits from.hex "0xfe" 16
print sumDigits from.hex "0xf0e" 16


package main

import (
    "fmt"
    "math/big"
    "strconv"
    "strings"
)

var suffixes = " KMGTPEZYXWVU"
var ggl = googol()

func googol() *big.Float {
    g1 := new(big.Float).SetPrec(500)
    g1.SetInt64(10000000000)
    g := new(big.Float)
    g.Set(g1)
    for i := 2; i <= 10; i++ {
        g.Mul(g, g1)
    }
    return g
}

func suffize(arg string) {
    fields := strings.Fields(arg)
    a := fields[0]
    if a == "" {
        a = "0"
    }
    var places, base int
    var frac, radix string
    switch len(fields) {
    case 1:
        places = -1
        base = 10
    case 2:
        places, _ = strconv.Atoi(fields[1])
        base = 10
        frac = strconv.Itoa(places)
    case 3:
        if fields[1] == "," {
            places = 0
            frac = ","
        } else {
            places, _ = strconv.Atoi(fields[1])
            frac = strconv.Itoa(places)
        }
        base, _ = strconv.Atoi(fields[2])
        if base != 2 && base != 10 {
            base = 10
        }
        radix = strconv.Itoa(base)
    }
    a = strings.Replace(a, ",", "", -1) // get rid of any commas
    sign := ""
    if a[0] == '+' || a[0] == '-' {
        sign = string(a[0])
        a = a[1:] // remove any sign after storing it
    }
    b := new(big.Float).SetPrec(500)
    d := new(big.Float).SetPrec(500)
    b.SetString(a)
    g := false
    if b.Cmp(ggl) >= 0 {
        g = true
    }
    if !g && base == 2 {
        d.SetUint64(1024)
    } else if !g && base == 10 {
        d.SetUint64(1000)
    } else {
        d.Set(ggl)
    }
    c := 0
    for b.Cmp(d) >= 0 && c < 12 { // allow b >= 1K if c would otherwise exceed 12
        b.Quo(b, d)
        c++
    }
    var suffix string
    if !g {
        suffix = string(suffixes[c])
    } else {
        suffix = "googol"
    }
    if base == 2 {
        suffix += "i"
    }
    fmt.Println("   input number =", fields[0])
    fmt.Println("  fraction digs =", frac)
    fmt.Println("specified radix =", radix)
    fmt.Print("     new number = ")
    if places >= 0 {
        fmt.Printf("%s%.*f%s\n", sign, places, b, suffix)
    } else {
        fmt.Printf("%s%s%s\n", sign, b.Text('g', 50), suffix)
    }
    fmt.Println()
}

func main() {
    tests := []string{
        "87,654,321",
        "-998,877,665,544,332,211,000      3",
        "+112,233                          0",
        "16,777,216                        1",
        "456,789,100,000,000",
        "456,789,100,000,000               2      10",
        "456,789,100,000,000               5       2",
        "456,789,100,000.000e+00           0      10",
        "+16777216                         ,       2",
        "1.2e101",
        "446,835,273,728                   1",
        "1e36",
        "1e39", // there isn't a big enough suffix for this one but it's less than googol
    }
    for _, test := range tests {
        suffize(test)
    }
}


(* ****** ****** *)
//
// How to compile:
// patscc -DATS_MEMALLOC_LIBC -o SumDigits SumDigits.dats
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)

extern
fun{a:[email protected]}
SumDigits(n: a, base: int): a

implement
{a}(*tmp*)
SumDigits(n, base) = let
//
val base = gnumber_int(base)
//
fun
loop (n: a, res: a): a =
  if gisgtz_val<a> (n)
    then loop (gdiv_val<a>(n, base), gadd_val<a>(res, gmod_val<a>(n, base)))
    else res
//
in
  loop (n, gnumber_int(0))
end // end of [SumDigits]

(* ****** ****** *)

val SumDigits_int = SumDigits<int>

(* ****** ****** *)

implement
main0 () =
{
//
val n = 1
val () = println! ("SumDigits(1, 10) = ", SumDigits_int(n, 10))
val n = 12345
val () = println! ("SumDigits(12345, 10) = ", SumDigits_int(n, 10))
val n = 123045
val () = println! ("SumDigits(123045, 10) = ", SumDigits_int(n, 10))
val n = 0xfe
val () = println! ("SumDigits(0xfe, 16) = ", SumDigits_int(n, 16))
val n = 0xf0e
val () = println! ("SumDigits(0xf0e, 16) = ", SumDigits_int(n, 16))
//
} (* end of [main0] *)


MsgBox % sprintf("%d %d %d %d %d`n"
	,SumDigits(1, 10)
	,SumDigits(12345, 10)
	,SumDigits(123045, 10)
	,SumDigits(0xfe, 16)
	,SumDigits(0xf0e, 16) )

SumDigits(n,base) {
	sum := 0
	while (n)
	{
		sum += Mod(n,base)
		n /= base
	}
	return sum
}

sprintf(s,fmt*) {
	for each, f in fmt
		StringReplace,s,s,`%d, % f
	return s
}


using Printf

const suf = Dict{BigInt, String}(BigInt(1) => "", BigInt(10)^100 => "googol",
    BigInt(10)^3 => "K", BigInt(10)^6 => "M", BigInt(10)^9 => "G", BigInt(10)^12 => "T",
    BigInt(10)^15 => "P", BigInt(10)^18 => "E", BigInt(10)^21 => "Z", BigInt(10)^24 => "Y",
    BigInt(10)^27 => "X", BigInt(10)^30 => "W", BigInt(10)^33 => "V", BigInt(10)^36 => "U")
const binsuf = Dict{BigInt, String}(BigInt(1) => "", BigInt(10)^100 => "googol",
    BigInt(2)^10 => "Ki", BigInt(2)^20 => "Mi", BigInt(2)^30 => "Gi", BigInt(2)^40 => "Ti",
    BigInt(2)^50 => "Pi", BigInt(2)^60 => "Ei", BigInt(2)^70 => "Zi", BigInt(2)^80 => "Yi",
    BigInt(2)^90 => "Xi", BigInt(2)^100 => "Wi", BigInt(2)^110 => "Vi", BigInt(2)^120 => "Ui")
const googol = BigInt(10)^100

function choosedivisor(n, base10=true)
    if n > 10 * googol
        return googol
    end
    s = base10 ? sort(collect(keys(suf))) : sort(collect(keys(binsuf)))
    (i = findfirst(x -> x > 0.001 * n, s)) == nothing ? s[end] : s[i]
end

pretty(x) = (floor(x) == x) ? string(BigInt(x)) : replace(@sprintf("%f", x), r"0+$" => "")

function suffize(val::String, rounddigits=-1, suffixbase=10)
    if val[1] == '-'
        isneg = true
        val = val[2:end]
    else
        isneg = false
        if val[1] == '+'
            val = val[2:end]
        end
    end
    val = replace(val, r"," => "")
    nval = (b = tryparse(BigInt, val)) == nothing ? parse(BigFloat, val) : b
    b = choosedivisor(nval, suffixbase != 2)
    mantissa = nval / b
    if rounddigits >= 0
        mantissa = round(mantissa, digits=rounddigits)
    end
    (isneg ? "-" : "") * pretty(mantissa) * (suffixbase == 10 ? suf[b] : binsuf[b])
end
suffize(val::Number, rounddigits=-1, suffixbase=10) = suffize(string(val), rounddigits, suffixbase)

testnumbers = [
   ["87,654,321"],
   ["-998,877,665,544,332,211,000", 3],
   ["+112,233", 0],
   ["16,777,216", 1],
   ["456,789,100,000,000"],
   ["456,789,100,000,000", 2, 10],
   ["456,789,100,000,000", 5, 2],
   ["456,789,100,000.000e+00", 0],
   ["+16777216", 0, 2],
   ["1.2e101"]]

for l in testnumbers
    n = length(l)
    s = (n == 1) ? suffize(l[1]) : (n == 2) ? suffize(l[1], l[2]) : suffize(l[1], l[2], l[3])
    println(lpad(l[1], 30), (n > 1) ? lpad(l[2], 3) : "   ",
                            (n > 2) ? lpad(l[3], 3) : "   ", " : ", s)
end


import math, strutils

const
  Suffixes = ["", "K", "M", "G", "T", "P", "E", "Z", "Y", "X", "W", "V", "U", "googol"]
  None = -1

proc suffize(num: string; digits = None; base = 10): string =

  let exponentDist = if base == 2: 10 else: 3
  let num = num.strip().replace(",", "")
  let numSign = if num[0] in {'+', '-'}: $num[0] else: ""

  var n = abs(num.parseFloat())
  var suffixIndex: int
  if base == 10 and n >= 1e100:
    suffixIndex = 13
    n /= 1e100
  elif n > 1:
    let magnitude = log(n, base.toFloat).int
    suffixIndex = min(magnitude div exponentDist, 12)
    n /= float(base ^ (exponentDist * suffixIndex))
  else:
    suffixIndex = 0

  let numStr = if digits > 0:
                 n.formatFloat(ffDecimal, precision = digits)
               elif digits == 0:
                 # Can’t use "formatFloat" with precision = 0 as it keeps the decimal point.
                 # So convert to nearest int and format this value.
                 $(n.toInt)
               else:
                 n.formatFloat(ffDecimal, precision = 3).strip(chars = {'0'}).strip(chars = {'.'})
  result = numSign & numStr & Suffixes[suffixIndex] & (if base == 2: "i" else: "")

when isMainModule:

  echo "[87,654,321]: ",
       suffize("87,654,321")
  echo "[-998,877,665,544,332,211,000 / digits = 3]: ",
       suffize("-998,877,665,544,332,211,000", 3)
  echo "[+112,233 / digits = 0]: ",
       suffize("+112,233", 0)
  echo "[16,777,216 / digits = 1]: ",
       suffize("16,777,216", 1)
  echo "[456,789,100,000,000 / digits = 2]: ",
       suffize("456,789,100,000,000", 2)
  echo "[456,789,100,000,000 / digits = 2 / base = 10]: ",
       suffize("456,789,100,000,000", 2, 10)
  echo "[456,789,100,000,000 / digits = 5 / base = 2]: ",
       suffize("456,789,100,000,000", digits = 5, base = 2)
  echo "[456,789,100,000.000e+000 / digits = 0 / base = 10]: ",
       suffize("456,789,100,000.000e+000", digits = 0, base = 10)
  echo "[+16777216 / base = 2]: ",
       suffize("+16777216", base = 2)
  echo "[1.2e101]: ",
       suffize("1.2e101")


#!/usr/bin/awk -f

BEGIN {
    print sumDigits("1")
    print sumDigits("12")
    print sumDigits("fe")
    print sumDigits("f0e")
}

function sumDigits(num,    nDigs, digits, sum, d, dig, val, sum) {
    nDigs = split(num, digits, "")
    sum = 0
    for (d = 1; d <= nDigs; d++) {
        dig = digits[d]
        val = digToDec(dig)
        sum += val
    }
    return sum
}

function digToDec(dig) {
    return index("0123456789abcdef", tolower(dig)) - 1
}


FUNCTION sumDigits(num AS STRING, bas AS LONG) AS LONG
    'can handle up to base 36
    DIM outp AS LONG
    DIM validNums AS STRING, tmp AS LONG, x AS LONG, lennum AS LONG, L0 AS LONG
    'ensure num contains only valid characters
    validNums = LEFT$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", bas)
    lennum = LEN(num)
    FOR L0 = lennum TO 1 STEP -1
        x = INSTR(validNums, UCASE$(MID$(num, L0, 1))) - 1
        IF -1 = x THEN EXIT FUNCTION
        tmp = tmp + (x * (bas ^ (lennum - L0)))
    NEXT
    WHILE tmp
        outp = outp + (tmp MOD bas)
        tmp = tmp \ bas
    WEND
    sumDigits = outp
END FUNCTION

PRINT sumDigits(LTRIM$(STR$(1)), 10)
PRINT sumDigits(LTRIM$(STR$(1234)), 10)
PRINT sumDigits(LTRIM$(STR$(&HFE)), 16)
PRINT sumDigits(LTRIM$(STR$(&HF0E)), 16)
PRINT sumDigits("2", 2)


include builtins/bigatom.e

constant suffixes = "KMGTPEZYXWVU",
         anydp = 100 -- the "any dp" value (prevents nearest 1e-100, though)

function suffize(sequence args)
    bigatom size = ba_abs(args[1])
    integer sgn = iff(ba_compare(args[1],0)<0?-1:+1),
            la = length(args),
            dp = iff(la>=2?args[2]:anydp),  -- decimal places
            bd = iff(la>=3?args[3]:10)      -- 2 or 10
    atom ip = power(10,dp) -- (inverted precision)
    if dp<0 then size = ba_round(size,ip) end if
    string suffix
    if ba_compare(size,1e100)>0 then
        size = ba_div(size,1e100)
        suffix = "googol"
    else
        integer factor = iff(bd=2?1024:1000), fdx = 0
        while fdx<length(suffixes) do
            bigatom rsize = ba_div(size,factor)
            if dp<0 then rsize = ba_round(rsize,ip) end if
            if ba_compare(rsize,1)<0 then exit end if
            size = rsize
            fdx += 1
        end while
        suffix = iff(fdx=0?"":suffixes[fdx]&iff(bd=2?"i":""))
    end if
    string fmt = iff(dp<0 or dp=anydp?"%0B":sprintf("%%0.%dB",dp))
    string res = ba_sprintf(fmt, ba_mul(size,sgn))
    res &= suffix
    return res
end function

constant test_text = """
 87,654,321
-998,877,665,544,332,211,000 3
+112,233 0
 16,777,216 1
456,789,100,000,000
456,789,100,000,000 2 10
456,789,100,000,000 5 2
456,789,100,000.000e+00 0 10
 16777216 , 2
1.2e101
347,344 -2
10
""",
test_cases = split(test_text,'\n',no_empty:=true)

for i=1 to length(test_cases) do
    string ti = test_cases[i]
    sequence args = split(ti,no_empty:=true)
    args[1] = ba_new(substitute(args[1],",",""))
    for a=2 to length(args) do
        sequence sa = scanf(args[a],"%f")
        args[a] = iff(length(sa)=1?sa[1][1]:anydp)
    end for
    string res = suffize(args)
    printf(1,"%30s : %s\n",{ti,res})
end for


      *FLOAT64
      PRINT "Digit sum of 1 (base 10) is "; FNdigitsum(1, 10)
      PRINT "Digit sum of 12345 (base 10) is "; FNdigitsum(12345, 10)
      PRINT "Digit sum of 9876543210 (base 10) is "; FNdigitsum(9876543210, 10)
      PRINT "Digit sum of FE (base 16) is "; ~FNdigitsum(&FE, 16) " (base 16)"
      PRINT "Digit sum of F0E (base 16) is "; ~FNdigitsum(&F0E, 16) " (base 16)"
      END

      DEF FNdigitsum(n, b)
      LOCAL q, s
      WHILE n <> 0
        q = INT(n / b)
        s += n - q * b
        n = q
      ENDWHILE
      = s


define s(n) {
    auto i, o, s

    o = scale
    scale = 0

    for (i = n; i > 0; i /= ibase) {
        s += i % ibase
    }

    scale = o
    return(s)
}

ibase = 10
s(1)
s(1234)
ibase = 16
s(FE)
s(F0E)


import math
import os

def suffize(num, digits=None, base=10):
    suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']

    exponent_distance = 10 if base == 2 else 3
    num = num.strip().replace(',', '')
    num_sign = num[0] if num[0] in '+-' else ''

    num = abs(float(num))

    if base == 10 and num >= 1e100:
        suffix_index = 13
        num /= 1e100
    elif num > 1:
        magnitude = math.floor(math.log(num, base))
        suffix_index = min(math.floor(magnitude / exponent_distance), 12)
        num /= base ** (exponent_distance * suffix_index)
    else:
        suffix_index = 0

    if digits is not None:
        num_str = f'{num:.{digits}f}'
    else:
        num_str = f'{num:.3f}'.strip('0').strip('.')

    return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')

tests = [('87,654,321',),
         ('-998,877,665,544,332,211,000', 3),
         ('+112,233', 0),
         ('16,777,216', 1),
         ('456,789,100,000,000', 2),
         ('456,789,100,000,000', 2, 10),
         ('456,789,100,000,000', 5, 2),
         ('456,789,100,000.000e+00', 0, 10),
         ('+16777216', None, 2),
         ('1.2e101',)]

for test in tests:
    print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))


sub sufficate ($val is copy, $type is copy = 'M', $round is copy = Any) {
   if +$type ~~ Int { $round = $type; $type = 'M' }
   my $s = '';
   if $val.substr(0,1) eq '-' { $s = '-'; $val.=substr(1) }
   $val.=subst(',', '', :g);
   if $val ~~ m:i/'e'/ {
       my ($m,$e) = $val.split(/<[eE]>/);
       $val = ($e < 0)
           ?? $m * FatRat.new(1,10**-$e)
           !! $m * 10**$e;
   }
   my %s = do given $type {
       when 'M' { <K M G T P E Z Y X W V U> Z=> (1000, * * 1000 … *) }
       when 'B' { <Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui> Z=> (1024, * * 1024 … *) }
       when 'G' { googol => 10**100 }
       default { return 'What we have here is a failure to communicate...' }
   }
   my $k = do given $val {
       when .abs < (my $m = min %s.values) { %s.first( *.value == $m ).key };
       when .abs > (my $x = max %s.values) { %s.first( *.value == $x ).key };
       default { %s.sort(*.value).first({$val.abs/%s{$_.key} < min %s.values}).key}
   }
   $round.defined
       ?? $s ~ comma(($val.abs/%s{$k}).round(10**-$round)) ~ $k
       !! $s ~ comma($val.abs/%s{$k}) ~ $k
}

sub comma ($i is copy) {
    my $s = $i < 0 ?? '-' !! '';
    my ($whole, $frac) = $i.split('.');
    $frac = $frac.defined ?? ".$frac" !! '';
    $s ~ $whole.abs.flip.comb(3).join(',').flip ~ $frac
}

## TESTING

my @tests =
   '87,654,321',
   '-998,877,665,544,332,211,000 3',
   '+112,233 0',
   '16,777,216 1',
   '456,789,100,000,000',
   '456,789,100,000,000 M 2',
   '456,789,100,000,000 B 5',
   '456,789,100,000.000e+00 M 0',
   '+16777216 B',
   '1.2e101 G',
   "{run('df', '/', :out).out.slurp.words[10] * 1024} B 2", # Linux df returns Kilobytes by default
   '347,344 M -2', # round to -2 past the decimal
   '1122334455 Q', # bad unit type example
;

printf "%33s : %s\n", $_, sufficate(|.words) for @tests;


get "libhdr"

let digitsum(n, base) =
    n=0 -> 0,
    n rem base + digitsum(n/base, base)

let start() be
$(  writef("%N*N", digitsum(1, 10))      // prints 1
    writef("%N*N", digitsum(1234, 10))   // prints 10
    writef("%N*N", digitsum(#1234, 8))   // also prints 10
    writef("%N*N", digitsum(#XFE, 16))   // prints 29
    writef("%N*N", digitsum(#XF0E, 16))  // also prints 29
$)


SumDigits ← {
  𝕊 𝕩: 10 𝕊 𝕩;
  𝕨 𝕊 0: 0;
  (𝕨|𝕩)+𝕨𝕊⌊𝕩÷𝕨
}

•Show SumDigits 1
•Show SumDigits 1234
•Show 16 SumDigits 254


/*REXX program to add a  (either metric or "binary" metric)  suffix to a decimal number.*/
@.=                                              /*default value for the stemmed array. */
parse arg @.1                                    /*obtain optional arguments from the CL*/
if @.1==''  then do;   @.1=   '   87,654,321                              '
                       @.2=   '  -998,877,665,544,332,211,000    3        '
                       @.3=   '  +112,233                        0        '
                       @.4=   '   16,777,216                     1        '

                       @.5=   '   456,789,100,000,000            2        '
                       @.5=   '   456,789,100,000,000                     '

                       @.6=   '   456,789,100,000,000            2    10  '
                       @.7=   '   456,789,100,000,000            5     2  '
                       @.8=   '   456,789,100,000.000e+00        0    10  '
                       @.9=   '   +16777216                      ,     2  '
                       @.10=  '   1.2e101                                 '
                       @.11=  '   134,112,411,648                1        '    /*via DIR*/
                 end                             /*@.11≡  amount of free space on my C: */

     do i=1  while @.i\==''; say copies("─", 60) /*display a separator betweenst values.*/
     parse var  @.i  x  f  r  .                  /*get optional arguments from the list.*/
     say '     input number='          x         /*show original number     to the term.*/
     say '    fraction digs='             f      /*  "  specified fracDigs   "  "    "  */
     say '  specified radix='                r   /*  "  specified radix      "  "    "  */
     say '       new number='  suffize(x, f, r)  /*maybe append an "alphabetic" suffix. */
     end   /*i*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
suffize: procedure; arg s 2 1 n,  f,  b          /*obtain:  sign, N, fractionDigs, base.*/
         if digits()<99  then numeric digits 500 /*use enough dec. digs for arithmetic. */
         @err = '***error*** (from SUFFIZE)  '   /*literal used when returning err msg. */
         if b==''  then b= 10;              o= b /*assume a base  (ten)  if omitted.    */
         n= space( translate(n,,','), 0);   m= n /*elide commas from the  1st  argument.*/
         f= space( translate(f,,','), 0)         /*elide commas from the  2nd  argument.*/
         if \datatype(n, 'N')  then return @err "1st argument isn't numeric."
         if f==''  then f= length(space(translate(n,,.), 0)) /*F omitted?  Use full len.*/
         if \datatype(f, 'W')  then return @err "2nd argument isn't an integer: "     f
         if f<0                then return @err "2nd argument can't be negative. "    f
         if \datatype(b, 'W')  then return @err "3rd argument isn't an integer. "     b
         if b\==10  &  b\==2   then return @err "3rd argument isn't a  10  or  2."    b
         if arg()>3            then return @err "too many arguments were specified."
         @=  ' KMGTPEZYXWVU'                     /*metric uppercase suffixes, with blank*/
         !.=;    !.2= 'i'                        /*set default suffix;  "binary" suffix.*/
         i= 3;   b= abs(b);  if b==2  then i= 10 /*a power of ten; or a power of  2**10 */
         if \datatype(n, 'N') | pos('E', n/1)\==0  then return m   /* ¬num or has an "E"*/
         sig=;    if s=='-' | s=="+"  then sig=s /*preserve the number's sign if present*/
         n= abs(n)                               /*possibly round number, & remove sign.*/

           do while n>=1e100 & b==10;  x=n/1e100 /*is N ≥ googol and base=10?  A googol?*/
           if pos(., x)\==0 & o<0  then leave    /*does # have a dec. point  or is B<0? */
           return sig  ||  x'googol'             /*maybe prepend the sign,  add GOOGOL. */
           end   /*while*/

           do j=length(@)-1  to 1  by -1  while n>0  /*see if #  is a multiple of 1024. */
           $= b ** (i*j)                             /*compute base raised to a power.  */
           if n<$  then iterate                      /*N not big enough?   Keep trying. */
           n= format(n/$, , min( digits(), f) ) / 1  /*reformat number with a fraction. */
           if pos(., n)\==0 & o<0  then return m     /*has a decimal point  or  is B<0? */
           leave                                     /*leave this DO loop at this point.*/
           end   /*j*/

         if n=0  then j=0                            /*N = 0?    Don't use any suffix.  */
         return sig||strip(n||substr(@, j+1,1))!.b   /*add sign, suffixes, strip blanks.*/


*        Sum of a series           30/03/2017
SUMSER   CSECT
         USING  SUMSER,12          base register
         LR     12,15              set addressability
         LR     10,14              save r14
         LE     4,=E'0'            s=0
         LE     2,=E'1'            i=1
       DO WHILE=(CE,2,LE,=E'1000') do i=1 to 1000
         LER    0,2                  i
         MER    0,2                  *i
         LE     6,=E'1'              1
         DER    6,0                  1/i**2
         AER    4,6                  s=s+1/i**2
         AE     2,=E'1'              i=i+1
       ENDDO    ,                  enddo i
         LA     0,4                format F13.4
         LER    0,4                s
         BAL    14,FORMATF         call formatf
         MVC    PG(13),0(1)        retrieve result
         XPRNT  PG,80              print buffer
         BR     10                 exit
         COPY   FORMATF            formatf code
PG       DC     CL80' '            buffer
         END    SUMSER


(defun sum-x^-2 (max-x)
   (if (zp max-x)
       0
       (+ (/ (* max-x max-x))
          (sum-x^-2 (1- max-x)))))


INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

PROC Calc(CARD n REAL POINTER res)
  CARD i,st
  BYTE perc
  REAL one,a,b

  IntToReal(0,res)
  IF n=0 THEN RETURN FI

  IntToReal(1,one)
  st=n/100
  FOR i=1 TO n
  DO
    IF i MOD st=0 THEN
      PrintB(perc) Put('%) PutE() Put(28)
      perc==+1
    FI

    IntToReal(i,a)
    RealMult(a,a,b)
    RealDiv(one,b,a)
    RealAdd(res,a,b)
    RealAssign(b,res)
  OD
RETURN

PROC Main()
  REAL POINTER res
  CARD n=[1000]

  Put(125) PutE() ;clear screen
  Calc(n,res)
  PrintF("s(%U)=",n)
  PrintRE(res)
RETURN


#include <stdio.h>

int SumDigits(unsigned long long n, const int base) {
    int sum = 0;
    for (; n; n /= base)
    	sum += n % base;
    return sum;
}

int main() {
    printf("%d %d %d %d %d\n",
        SumDigits(1, 10),
        SumDigits(12345, 10),
        SumDigits(123045, 10),
        SumDigits(0xfe, 16),
        SumDigits(0xf0e, 16) );
    return 0;
}


namespace RosettaCode.SumDigitsOfAnInteger
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    internal static class Program
    {
        /// <summary>
        ///     Enumerates the digits of a number in a given base.
        /// </summary>
        /// <param name="number"> The number. </param>
        /// <param name="base"> The base. </param>
        /// <returns> The digits of the number in the given base. </returns>
        /// <remarks>
        ///     The digits are enumerated from least to most significant.
        /// </remarks>
        private static IEnumerable<int> Digits(this int number, int @base = 10)
        {
            while (number != 0)
            {
                int digit;
                number = Math.DivRem(number, @base, out digit);
                yield return digit;
            }
        }

        /// <summary>
        ///     Sums the digits of a number in a given base.
        /// </summary>
        /// <param name="number"> The number. </param>
        /// <param name="base"> The base. </param>
        /// <returns> The sum of the digits of the number in the given base. </returns>
        private static int SumOfDigits(this int number, int @base = 10)
        {
            return number.Digits(@base).Sum();
        }

        /// <summary>
        ///     Demonstrates <see cref="SumOfDigits" />.
        /// </summary>
        private static void Main()
        {
            foreach (var example in
                new[]
                {
                    new {Number = 1, Base = 10},
                    new {Number = 12345, Base = 10},
                    new {Number = 123045, Base = 10},
                    new {Number = 0xfe, Base = 0x10},
                    new {Number = 0xf0e, Base = 0x10}
                })
            {
                Console.WriteLine(example.Number.SumOfDigits(example.Base));
            }
        }
    }
}


Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String
    Dim suffix As String, parts() As String, exponent As String
    Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean
    flag = False
    fractiondigits = Val(sfractiondigits)
    suffixes = " KMGTPEZYXWVU"
    number = Replace(number, ",", "", 1)
    Dim c As Currency
    Dim sign As Integer
    'separate leading sign
    If Left(number, 1) = "-" Then
        number = Right(number, Len(number) - 1)
        outstring = "-"
    End If
    If Left(number, 1) = "+" Then
        number = Right(number, Len(number) - 1)
        outstring = "+"
    End If
    'split exponent
    parts = Split(number, "e")
    number = parts(0)
    If UBound(parts) > 0 Then exponent = parts(1)
    'split fraction
    parts = Split(number, ".")
    number = parts(0)
    If UBound(parts) > 0 Then frac = parts(1)
    If base = "2" Then
        Dim cnumber As Currency
        cnumber = Val(number)
        nsuffix = 0
        Dim dnumber As Double
        If cnumber > 1023 Then
            cnumber = cnumber / [email protected]
            nsuffix = nsuffix + 1
            dnumber = cnumber
            Do While dnumber > 1023
                dnumber = dnumber / [email protected] 'caveat: currency has only 4 fractional digits ...
                nsuffix = nsuffix + 1
            Loop
            number = CStr(dnumber)
        Else
            number = CStr(cnumber)
        End If
        leadingstring = Int(number)
        number = Replace(number, ",", "")

        leading = Len(leadingstring)
        suffix = Mid(suffixes, nsuffix + 1, 1)
    Else
        'which suffix
        nsuffix = (Len(number) + Val(exponent) - 1) \ 3
        If nsuffix < 13 Then
            suffix = Mid(suffixes, nsuffix + 1, 1)
            leading = (Len(number) - 1) Mod 3 + 1
            leadingstring = Left(number, leading)
        Else
            flag = True
            If nsuffix > 32 Then
                suffix = "googol"
                leading = Len(number) + Val(exponent) - 99
                leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), "0")
            Else
                suffix = "U"
                leading = Len(number) + Val(exponent) - 35
                If Val(exponent) > 36 Then
                    leadingstring = number & String$(Val(exponent) - 36, "0")
                Else
                    leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))
                End If
            End If
        End If
    End If
    'round up if necessary
    If fractiondigits > 0 Then
        If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then
            fraction = Mid(number, leading + 1, fractiondigits - 1) & _
                CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)
        Else
            fraction = Mid(number, leading + 1, fractiondigits)
        End If
    Else
        If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> "" And sfractiondigits <> "," Then
            leadingstring = Mid(number, 1, leading - 1) & _
                CStr(Val(Mid(number, leading, 1)) + 1)
        End If
    End If
    If flag Then
        If sfractiondigits = "" Or sfractiondigits = "," Then
            fraction = ""
        End If
    Else
        If sfractiondigits = "" Or sfractiondigits = "," Then
            fraction = Right(number, Len(number) - leading)
        End If
    End If
    outstring = outstring & leadingstring
    If Len(fraction) > 0 Then
        outstring = outstring & "." & fraction
    End If
    If base = "2" Then
        outstring = outstring & suffix & "i"
    Else
        outstring = outstring & suffix
    End If
    suffize = outstring
End Function
Sub program()
    Dim s(10) As String, t As String, f As String, r As String
    Dim tt() As String, temp As String
    s(0) = "               87,654,321"
    s(1) = "          -998,877,665,544,332,211,000      3"
    s(2) = "          +112,233                          0"
    s(3) = "           16,777,216                       1"
    s(4) = "           456,789,100,000,000              2"
    s(5) = "           456,789,100,000,000              2      10"
    s(6) = "           456,789,100,000,000              5       2"
    s(7) = "           456,789,100,000.000e+00          0      10"
    s(8) = "          +16777216                         ,       2"
    s(9) = "           1.2e101"
    For i = 0 To 9
        ReDim tt(0)
        t = Trim(s(i))
        Do
            temp = t
            t = Replace(t, "  ", " ")
        Loop Until temp = t
        tt = Split(t, " ")
        If UBound(tt) > 0 Then f = tt(1) Else f = ""
        If UBound(tt) > 1 Then r = tt(2) Else r = ""
        Debug.Print String$(48, "-")
        Debug.Print "     input number = "; tt(0)
        Debug.Print "    fraction digs = "; f
        Debug.Print "  specified radix = "; r
        Debug.Print "       new number = "; suffize(tt(0), f, r)
    Next i
End Sub


import "/big" for BigRat
import "/fmt" for Fmt

var suffixes = " KMGTPEZYXWVU"
var googol = BigRat.fromDecimal("1e100")

var suffize = Fn.new { |arg|
    var fields = arg.split(" ").where { |s| s != "" }.toList
    if (fields.isEmpty) fields.add("0")
    var a = fields[0]
    var places
    var base
    var frac  = ""
    var radix = ""
    var fc = fields.count
    if (fc == 1) {
        places = -1
        base = 10
    } else if (fc == 2) {
        places = Num.fromString(fields[1])
        base = 10
        frac = places.toString
    } else if (fc == 3) {
        if (fields[1] == ",") {
            places = 0
            frac = ","
        } else {
            places = Num.fromString(fields[1])
            frac = places.toString
        }
        base = Num.fromString(fields[2])
        if (base !=2 && base != 10) base = 10
        radix = base.toString
    }
    a = a.replace(",", "") // get rid of any commas
    var sign = ""
    if (a[0] == "+" || a[0] == "-") {
        sign = a[0]
        a = a[1..-1] // remove any sign after storing it
    }
    var b = BigRat.fromDecimal(a)
    var g = b >= googol
    var d = (!g && base ==  2) ? BigRat.new(1024, 1) :
            (!g && base == 10) ? BigRat.new(1000, 1) : googol.copy()
    var c = 0
    while (b >= d && c < 12) { // allow b >= 1K if c would otherwise exceed 12
        b = b / d
        c = c + 1
    }
    var suffix = !g ? suffixes[c] : "googol"
    if (base == 2) suffix = suffix + "i"
    System.print("   input number = %(fields[0])")
    System.print("  fraction digs = %(frac)")
    System.print("specified radix = %(radix)")
    System.write("     new number = ")
    BigRat.showAsInt = true
    if (places >= 0) {
        Fmt.print("$0s$s$s", sign, b.toDecimal(places), suffix)
    } else {
        Fmt.print("$0s$s$s", sign, b.toDecimal, suffix)
    }
    System.print()
}

var tests = [
    "87,654,321",
    "-998,877,665,544,332,211,000      3",
    "+112,233                          0",
    "16,777,216                        1",
    "456,789,100,000,000",
    "456,789,100,000,000               2      10",
    "456,789,100,000,000               5       2",
    "456,789,100,000.000e+00           0      10",
    "+16777216                         ,       2",
    "1.2e101",
    "446,835,273,728                   1",
    "1e36",
    "1e39", // there isn't a big enough suffix for this one but it's less than googol
]
for (test in tests) suffize.call(test)


function partialSum(n:uint):Number
{
	var sum:Number = 0;
	for(var i:uint = 1; i <= n; i++)
		sum += 1/(i*i);
	return sum;
}
trace(partialSum(1000));


with Ada.Text_Io; use Ada.Text_Io;

procedure Sum_Series is
   function F(X : Long_Float) return Long_Float is
   begin
      return 1.0 / X**2;
   end F;
   package Lf_Io is new Ada.Text_Io.Float_Io(Long_Float);
   use Lf_Io;
   Sum : Long_Float := 0.0;
   subtype Param_Range is Integer range 1..1000;
begin
   for I in Param_Range loop
      Sum := Sum + F(Long_Float(I));
   end loop;
   Put("Sum of F(x) from" & Integer'Image(Param_Range'First) &
      " to" & Integer'Image(Param_Range'Last) & " is ");
   Put(Item => Sum, Aft => 10, Exp => 0);
   New_Line;
end Sum_Series;


#include <iostream>
#include <cmath>
int SumDigits(const unsigned long long int digits, const int BASE = 10) {
    int sum = 0;
    unsigned long long int x = digits;
    for (int i = log(digits)/log(BASE); i>0; i--){
        const double z = std::pow(BASE,i);
	  const unsigned long long int t = x/z;
	  sum += t;
	  x -= t*z;
    }
    return x+sum;
}

int main() {
        std::cout << SumDigits(1) << ' '
                  << SumDigits(12345) << ' '
                  << SumDigits(123045) << ' '
                  << SumDigits(0xfe, 16) << ' '
                  << SumDigits(0xf0e, 16) << std::endl;
        return 0;
}


(defn sum-digits [n base]
  (let [number (if-not (string? n) (Long/toString n base) n)]
    (reduce + (map #(Long/valueOf (str %) base) number))))


var [const] BI=Import.lib("zklBigNum");  // GMP
var metric, binary, googol=BI("1e100");
metric,binary = metricBin();

   // suffix: "2" (binary), "10" (metric)
   // For this task, we'll assume BF numbers and treat everything as a big int
fcn sufficate(numStr, fracDigits=",", suffix="10"){
   var [const] numRE=RegExp(0'^\+*(([+-]*\.*\d+)[.]*(\d*)(e*[+-]*\d*))^);

   numRE.search((numStr - " ,").toLower());
   r:=numRE.matched[1];
   if(not r.find(".")) r=BI(r); // else ((((0,7),"1.2e101","1","2","e101")
   else  // convert float ("1.2" or "1.2e10") to big int
      r=BI(numRE.matched[2,*].concat())/(10).pow(numRE.matched[3].len());

   if(fracDigits==",") fracDigits=0; # "digits past decimal or none, if not specified"
   else                fracDigits=fracDigits.toInt();

   suffix=suffix.strip().toInt();
   if(suffix==2) nms,szs :=binary;
   else if(suffix==10)   nms,szs :=metric;
   else //throw(Exception.ValueError("Invalid suffix: %s".fmt(suffix)));
     return("Invalid suffix");

   ar:=r.abs();
   if(ar<szs[0]) return(r.toString());	// little bitty number
   i,sz,nm := szs.filter1n('>(ar)) - 1, szs[i], nms[i];  // False - 1 == True
   if(i==True)  // r > biggest unit
      if(r>=googol) sz,nm = googol, "googol";   // get out the big hammer
      else          sz,nm = szs[-1], nms[-1];   //    even if they want n^2
   fd,m := fracDigits + 4, BI(10).pow(fd);      // int --> float w/extra digits
   a,f,a := r*m/sz, (a%m).toFloat()/m, f + a/m; // to float for rounding
   fmt:="%%,.%df%%s".fmt(fracDigits).fmt;	// eg "%,.5f%s"
   return(fmt(a,nm));
}

   //-->Metric:(("K", "M",..), (1000,1000000,..))
   //   Bin:   (("Ki","Mi",..),(1024,1048576,..))
fcn metricBin{
   ss,m,b := "K M G T P E Z Y X W V U".split(), List(),List();
   ss.zipWith(m.append,[3..3*(ss.len()),3].apply(BI(10).pow)); // Metric
   ss.apply("append","i")
      .zipWith(b.append,[10..10*(ss.len()),10].apply(BI(2).pow)); // Binary
   return(m.filter22("".isType), b.filter22("".isType)); # split to ((strings),(nums))
}


real
Invsqr(real n)
{
    1 / (n * n);
}

integer
main(void)
{
    integer i;
    real sum;

    sum = 0;

    i = 1;
    while (i < 1000) {
        sum += Invsqr(i);
        i += 1;
    }

    o_real(14, sum);
    o_byte('\n');

    0;
}


MODE RANGE = STRUCT(INT lwb, upb);

PROC sum = (PROC (INT)LONG REAL f, RANGE range)LONG REAL:(
  LONG REAL sum := LENG 0.0;
  FOR i FROM lwb OF range TO upb OF range DO
     sum := sum + f(i)
  OD;
  sum
);

test:(
  RANGE range = (1,1000);
  PROC f = (INT x)LONG REAL: LENG REAL(1) / LENG REAL(x)**2;
  print(("Sum of f(x) from ", whole(lwb OF range, 0), " to ",whole(upb OF range, 0)," is ", fixed(SHORTEN sum(f,range),-8,5),".", new line))
)


(defun sum-digits (number base)
  (loop for n = number then q
        for (q r) = (multiple-value-list (truncate n base))
        sum r until (zerop q)))


include "cowgol.coh";

sub digitSum(n: uint32, base: uint32): (r: uint32) is
    r := 0;
    while n > 0 loop
        r := r + n % base;
        n := n / base;
    end loop;
end sub;

print_i32(digitSum(1, 10)); # prints 1
print_nl();
print_i32(digitSum(1234, 10)); # prints 10
print_nl();
print_i32(digitSum(0xFE, 16)); # prints 29
print_nl();
print_i32(digitSum(0xF0E, 16)); # prints 29
print_nl();


class String
  def sum_digits(base : Int) : Int32
  	self.chars.reduce(0) { |acc, c|
  		value = c.to_i(base)
  		acc += value
  	}
  end
end

puts("1".sum_digits 10)
puts("1234".sum_digits 10)
puts("fe".sum_digits 16)
puts("f0e".sum_digits 16)


F sum35(limit)
   V sum = 0
   L(i) 1 .< limit
      I i % 3 == 0 | i % 5 == 0
         sum += i
   R sum

print(sum35(1000))


begin % compute the sum of 1/k^2 for k = 1..1000 %
    integer k;
    % computes the sum of a series from lo to hi using Jensen's Device %
    real procedure sum  ( integer %name% k; integer value lo, hi; real procedure term );
    begin
        real temp;
        temp := 0;
        k := lo;
        while k <= hi do begin
            temp := temp + term;
            k := k + 1
        end while_k_le_temp;
        temp
    end;
    write( r_format := "A", r_w := 8, r_d := 5, sum( k, 1, 1000, 1 / ( k * k ) ) )
end.


----------------------- SUM OF SERIES ----------------------

-- seriesSum :: Num a => (a -> a) -> [a] -> a
on seriesSum(f, xs)
    script go
        property mf : |λ| of mReturn(f)
        on |λ|(a, x)
            a + mf(x)
        end |λ|
    end script

    foldl(go, 0, xs)
end seriesSum

---------------------------- TEST --------------------------

-- inverseSquare :: Num -> Num
on inverseSquare(x)
    1 / (x ^ 2)
end inverseSquare

on run
    seriesSum(inverseSquare, enumFromTo(1, 1000))

    --> 1.643934566682
end run

--------------------- GENERIC FUNCTIONS --------------------

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m ≤ n then
        set lst to {}
        repeat with i from m to n
            set end of lst to i
        end repeat
        lst
    else
        {}
    end if
end enumFromTo

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn


import std.stdio, std.bigint;

uint sumDigits(T)(T n, in uint base=10) pure nothrow
in {
    assert(base > 1);
} body {
    typeof(return) total = 0;
    for ( ; n; n /= base)
        total += n % base;
    return total;
}

void main() {
    1.sumDigits.writeln;
    1_234.sumDigits.writeln;
    sumDigits(0xfe, 16).writeln;
    sumDigits(0xf0e, 16).writeln;
    1_234.BigInt.sumDigits.writeln;
}


[ I ~ S! d 0!=S L! + ] sS

1 lS x p
1234 lS x p
16 i
FE lS x p
F0E lS x p


needs combinators/bi

: mul3or5?  ( 3 mod 0 = ) ( 5 mod 0 = ) bi or ;

"The sum of the multiples of 3 or 5 below 1000 is " .
0 ( mul3or5? if I n:+ then ) 1 999 loop . cr

with: n

: >triangular SED: n -- n
    dup 1+ * 2 / ;

: sumdiv SED: n n -- n
    dup >r /mod nip >triangular r> * ;

: sumdiv_3,5 SED: n -- n
    ( swap sumdiv ) curry [3, 5, 15] swap a:map a:open neg + + ;

;with

"For 10^20 - 1, the sum is " .  10 20 ^ 1- sumdiv_3,5 . cr
bye


*        Sum multiples of 3 and 5
SUM35    CSECT
         USING  SUM35,R13          base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         STM    R14,R12,12(R13)    save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
         LA     R9,1               n=1
         LA     R7,7               do j=7 to 1 step -1
LOOPJ    MH     R9,=H'10'            n=n*10
         LR     R10,R9               n
         BCTR   R10,0                n-1
         ZAP    SUM,=PL8'0'          sum=0
         LA     R6,3                 i=3
       DO WHILE=(CR,R6,LE,R10)       do i=3 to n-1
         LR     R4,R6                  i
         SRDA   R4,32
         D      R4,=F'3'               i/3
         LTR    R4,R4                  if mod(i,3)=0
         BZ     CVD
         LR     R4,R6                  i
         SRDA   R4,32
         D      R4,=F'5'               i/5
         LTR    R4,R4                  if  mod(i,5)=0
         BNZ    ITERI
CVD      CVD    R6,IP                  ip=p
         AP     SUM,IP                 sum=sum+i
ITERI    LA     R6,1(R6)               i++
       ENDDO    ,                    enddo i
         XDECO  R9,PG                n
         MVC    PG+15(16),EM16       load mask
         ED     PG+15(16),SUM        packed dec (PL8) to char (CL16)
         XPRNT  PG,L'PG              print
         BCT    R7,LOOPJ           enddo j
         L      R13,4(0,R13)       restore previous savearea pointer
         LM     R14,R12,12(R13)    restore previous context
         XR     R15,R15            rc=0
         BR     R14                exit
SUM      DS     PL8
IP       DS     PL8
EM16     DC     X'40202020202020202020202020202120'  mask CL16 15num
PG       DC     CL80'123456789012 : 1234567890123456'
         YREGS
         END    SUM35


series: map 1..1000 => [1.0/&^2]
print [sum series]


SetFormat, FloatFast, 0.15
While A_Index <= 1000
 sum += 1/A_Index**2
MsgBox,% sum  ;1.643934566681554


func digits(num, bas = 10) {
    while num != 0 {
        let (n, digit) = (num / bas, num % bas)
        num = n
        yield digit
    }
}

func Iterator.Sum(acc = 0) {
    for x in this {
        acc += x
    }
    return acc
}

func sumOfDigits(num, bas = 10) => digits(num, bas).Sum()

for e in [
    (num: 1, bas: 10),
    (num: 12345, bas: 10),
    (num: 123045, bas:10),
    (num: 0xfe, bas: 16),
    (num: 0xf0e, bas: 16)
    ] {
    print(sumOfDigits(e.num, e.bas))
}


defmodule RC do
  def sumDigits(n, base\\10)
  def sumDigits(n, base) when is_integer(n) do
    Integer.digits(n, base) |> Enum.sum
  end
  def sumDigits(n, base) when is_binary(n) do
    String.codepoints(n) |> Enum.map(&String.to_integer(&1, base)) |> Enum.sum
  end
end

Enum.each([{1, 10}, {1234, 10}, {0xfe, 16}, {0xf0e, 16}], fn {n,base} ->
  IO.puts "#{Integer.to_string(n,base)}(#{base}) sums to #{ RC.sumDigits(n,base) }"
end)
IO.puts ""
Enum.each([{"1", 10}, {"1234", 10}, {"fe", 16}, {"f0e", 16}], fn {n,base} ->
  IO.puts "#{n}(#{base}) sums to #{ RC.sumDigits(n,base) }"
end)


INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

PROC Main()
  REAL sum,r
  INT i

  Put(125) PutE() ;clear the screen
  IntToReal(0,sum)
  FOR i=0 TO 999
  DO
    IF i MOD 3=0 OR i MOD 5=0 THEN
      IntToReal(i,r)
      RealAdd(sum,r,sum)
    FI
  OD

  PrintRE(sum)
RETURN


with Ada.Text_IO;

procedure Sum_Multiples is

   type Natural is range 0 .. 2**63 - 1;

   function Sum_3_5 (Limit : in Natural) return Natural is
      Sum : Natural := 0;
   begin
      for N in 1 .. Limit - 1 loop
         if N mod 3 = 0 or else N mod 5 = 0 then
            Sum := Sum + N;
         end if;
      end loop;
      return Sum;
   end Sum_3_5;

begin
   Ada.Text_IO.Put_Line ("n=1000: " & Sum_3_5 (1000)'Image);
   Ada.Text_IO.Put_Line ("n=5e9 : " & Sum_3_5 (5e9)'Image);
end Sum_Multiples;


FUNCTION s(x%)
   s = 1 / x ^ 2
END FUNCTION

FUNCTION sum(low%, high%)
   ret = 0
   FOR i = low TO high
      ret = ret + s(i)
   NEXT i
   sum = ret
END FUNCTION
PRINT sum(1, 1000)


(defun digit-sum (n)
  (apply #'+ (mapcar (lambda (c) (- c ?0)) (string-to-list "123"))))

(digit-sum 1234) ;=> 10


-module(sum_digits).
-export([sum_digits/2, sum_digits/1]).

sum_digits(N) ->
    sum_digits(N,10).

sum_digits(N,B) ->
    sum_digits(N,B,0).

sum_digits(0,_,Acc) ->
    Acc;
sum_digits(N,B,Acc) when N < B ->
    Acc+N;
sum_digits(N,B,Acc) ->
    sum_digits(N div B, B, Acc + (N rem B)).


# returns the sum of the multiples of 3 and 5 below n #
PROC sum of multiples of 3 and 5 below = ( LONG LONG INT n )LONG LONG INT:
     BEGIN
        # calculate the sum of the multiples of 3 below n #
        LONG LONG INT multiples of  3 = ( n - 1 ) OVER  3;
        LONG LONG INT multiples of  5 = ( n - 1 ) OVER  5;
        LONG LONG INT multiples of 15 = ( n - 1 ) OVER 15;
        ( # twice the sum of multiples of  3 #
          (  3 * multiples of  3 * ( multiples of  3 + 1 ) )
          # plus twice the sum of multiples of  5 #
        + (  5 * multiples of  5 * ( multiples of  5 + 1 ) )
          # less twice the sum of multiples of 15 #
        - ( 15 * multiples of 15 * ( multiples of 15 + 1 ) )
        ) OVER 2
    END # sum of multiples of 3 and 5 below # ;

print( ( "Sum of multiples of 3 and 5 below 1000: "
       , whole( sum of multiples of 3 and 5 below( 1000 ), 0 )
       , newline
       )
     );
print( ( "Sum of multiples of 3 and 5 below 1e20: "
       , whole( sum of multiples of 3 and 5 below( 100 000 000 000 000 000 000 ), 0 )
       , newline
       )
     )


define f(x) {
    return(1 / (x * x))
}

define s(n) {
    auto i, s

    for (i = 1; i <= n; i++) {
        s += f(i)
    }

    return(s)
}

scale = 20
s(1000)


beads 1 program 'Sum of a series'
calc main_init
	var k = 0
	loop reps:1000 count:n
		k = k + 1/n^2
	log to_str(k)


digitSum
=LAMBDA(s,
    FOLDROW(
        LAMBDA(a,
            LAMBDA(c,
                a + digitValue(c)
            )
        )
    )(0)(
        CHARSROW(s)
    )
)

digitValue
=LAMBDA(c,
    LET(
        ic, UNICODE(MID(c, 1, 1)),

        IF(AND(47 < ic, 58 > ic),
            ic - 48,
            IF(AND(64 < ic, 91 > ic),
                10 + (ic - 65),
                IF(AND(96 < ic, 123 > ic),
                    10 + (ic - 97),
                    0
                )
            )
        )
    )
)


# இது ஒரு எழில் தமிழ் நிரலாக்க மொழி உதாரணம்

# sum of digits of a number
# எண்ணிக்கையிலான இலக்கங்களின் தொகை

நிரல்பாகம் எண்_கூட்டல்( எண் )
  தொகை = 0
  @( எண் > 0 ) வரை
     d = எண்%10;
     பதிப்பி "digit = ",d
     எண் = (எண்-d)/10;
     தொகை  = தொகை  + d
  முடி
  பின்கொடு தொகை
முடி

பதிப்பி எண்_கூட்டல்( 1289)#20
பதிப்பி எண்_கூட்டல்( 123456789)# 45


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

-- sum35 :: Int -> Int
on sum35(n)
    tell sumMults(n)
        |λ|(3) + |λ|(5) - |λ|(15)
    end tell
end sum35

-- sumMults :: Int -> Int -> Int
on sumMults(n)
    -- Area under straight line
    -- between first multiple and last.
    script
        on |λ|(m)
            set n1 to (n - 1) div m
            m * n1 * (n1 + 1) div 2
        end |λ|
    end script
end sumMults

--------------------------- TEST ---------------------------
on run
    -- sum35Result :: String -> Int -> Int -> String
    script sum35Result
        -- sums of all multiples of 3 or 5 below or equal to N
        -- for N = 10 to N = 10E8 (limit of AS integers)
        on |λ|(a, x, i)
            a & "10" & i & " -> " & ¬
                sum35(10 ^ x) & "
"
        end |λ|
    end script
    foldl(sum35Result, "", enumFromTo(1, 8))
end run

-------------------- GENERIC FUNCTIONS ---------------------

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m > n then
        set d to -1
    else
        set d to 1
    end if
    set lst to {}
    repeat with i from m to n by d
        set end of lst to i
    end repeat
    return lst
end enumFromTo

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn


open System

let digsum b n =
    let rec loop acc = function
        | n when n > 0 ->
            let m, r = Math.DivRem(n, b)
            loop (acc + r) m
        | _ -> acc
    loop 0 n

[<EntryPoint>]
let main argv =
    let rec show = function
        | n :: b :: r -> printf " %d" (digsum b n); show r
        | _ -> ()

    show [1; 10; 1234; 10; 0xFE; 16; 0xF0E; 16]     // ->  1 10 29 29
    0


: sum-digits ( base n -- sum ) 0 swap [ dup zero? ] [ pick /mod swapd + swap ] until drop nip ;

{ 10 10 16 16 } { 1 1234 0xfe 0xf0e } [ sum-digits ] 2each


sumMul35: function [n][
	sum select 1..n-1 [x][or? 0=x%3 0=x%5]
]

print sumMul35 1000


n := 1000

msgbox % "Sum is " . Sum3_5(n)   . " for n = " . n
msgbox % "Sum is " . Sum3_5_b(n) . " for n = " . n

;Standard simple Implementation.
Sum3_5(n) {
	sum := 0
	loop % n-1 {
		if (!Mod(a_index,3) || !Mod(a_index,5))
		sum:=sum+A_index
	}
	return sum
}

;Translated from the C++ version.
Sum3_5_b( i ) {
	sum := 0, a := 0
	while (a < 28)
	{
		if (!Mod(a,3) || !Mod(a,5))
		{
			sum += a
			s := 30
			while (s < i)
			{
				if (a+s < i)
					sum += (a+s)
				s+=30
			}
		}
		a+=1
	}
	return sum
}


#include <stdio.h>

double Invsqr(double n)
{
	return 1 / (n*n);
}

int main (int argc, char *argv[])
{
	int i, start = 1, end = 1000;
	double sum = 0.0;

	for( i = start; i <= end; i++)
		sum += Invsqr((double)i);

	printf("%16.14f\n", sum);

	return 0;
}


class Program
{
    static void Main(string[] args)
    {
        // Create and fill a list of number 1 to 1000

        List<double> myList = new List<double>();
        for (double i = 1; i < 1001; i++)
        {
            myList.Add(i);
        }
        // Calculate the sum of 1/x^2

        var sum = myList.Sum(x => 1/(x*x));

        Console.WriteLine(sum);
        Console.ReadLine();
    }
}


: sum_int 0 begin over while swap base @ /mod swap rot + repeat nip ;

 2 base ! 11110 sum_int decimal  . cr
10 base ! 12345 sum_int decimal  . cr
16 base ! f0e   sum_int decimal  . cr


!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Fri Jun  7 21:00:12
!
!a=./f && make $a && $a
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
!f.f08:57.29:
!
!  subroutine process1(fmt,s,b)
!                             1
!Warning: Unused dummy argument 'b' at (1)
!digit sum       n
!        1 1
!       10 1234
!       29 fe
!       29 f0e
! sum of digits of n expressed in base is...
!      n   base    sum
!      1     10      1
!   1234     10     10
!    254     16     29
!   3854     16     29
!
!Compilation finished at Fri Jun  7 21:00:12

module base_mod
  private :: reverse
contains
  subroutine reverse(a)
    integer, dimension(:), intent(inout) :: a
    integer :: i, j, t
    do i=1,size(a)/2
       j = size(a) - i + 1
       t = a(i)
       a(i) = a(j)
       a(j) = t
    end do
  end subroutine reverse

  function antibase(b, n) result(a)
    integer, intent(in) :: b,n
    integer, dimension(32) :: a
    integer :: m, i
    a = 0
    m = n
    i = 1
    do while (m .ne. 0)
       a(i) = mod(m, b)
       m = m/b
       i = i+1
    end do
    call reverse(a)
  end function antibase
end module base_mod

program digit_sum
  use base_mod
  call still
  call confused
contains
  subroutine still
    character(len=6),parameter :: fmt = '(i9,a)'
    print'(a9,a8)','digit sum','n'
    call process1(fmt,'1',10)
    call process1(fmt,'1234',10)
    call process1(fmt,'fe',16)
    call process1(fmt,'f0e',16)
  end subroutine still

  subroutine process1(fmt,s,b)
    character(len=*), intent(in) :: fmt, s
    integer, intent(in), optional :: b
    integer :: i
    print fmt,sum((/(index('123456789abcdef',s(i:i)),i=1,len(s))/)),' '//s
  end subroutine process1

  subroutine confused
    character(len=5),parameter :: fmt = '(3i7)'
    print*,'sum of digits of n expressed in base is...'
    print'(3a7)','n','base','sum'
    call process0(10,1,fmt)
    call process0(10,1234,fmt)
    call process0(16,254,fmt)
    call process0(16,3854,fmt)
  end subroutine confused

  subroutine process0(b,n,fmt)
    integer, intent(in) :: b, n
    character(len=*), intent(in) :: fmt
    print fmt,n,b,sum(antibase(b, n))
  end subroutine process0
end program digit_sum


#!/usr/bin/awk -f
{
	n = $1-1;
	print sum(n,3)+sum(n,5)-sum(n,15);
}
function sum(n,d) {
	m = int(n/d);
	return (d*m*(m+1)/2);
}


Declare function mulsum35(n as integer) as integer
Function mulsum35(n as integer) as integer
    Dim s as integer
    For i as integer = 1 to n - 1
        If (i mod 3 = 0) or (i mod 5 = 0) then
            s += i
        End if
    Next i
    Return s
End Function
Print mulsum35(1000)
Sleep
End


#include <iostream>

double f(double x);

int main()
{
    unsigned int start = 1;
    unsigned int end = 1000;
    double sum = 0;

    for( unsigned int x = start; x <= end; ++x )
    {
        sum += f(x);
    }
    std::cout << "Sum of f(x) from " << start << " to " << end << " is " << sum << std::endl;
    return 0;
}

double f(double x)
{
    return ( 1.0 / ( x * x ) );
}


(deffunction S (?x) (/ 1 (* ?x ?x)))
(deffunction partial-sum-S
  (?start ?stop)
  (bind ?sum 0)
  (loop-for-count (?i ?start ?stop) do
    (bind ?sum (+ ?sum (S ?i)))
  )
  (return ?sum)
)


' FB 1.05.0 Win64

Function SumDigits(number As Integer, nBase As Integer) As Integer
  If number < 0 Then number = -number  ' convert negative numbers to positive
  If nBase < 2 Then nBase = 2   ' nBase can't be less than 2
  Dim As Integer sum = 0
  While number > 0
    sum += number Mod nBase
    number \= nBase
  Wend
  Return sum
End Function

Print "The sums of the digits are:"
Print
Print "1    base 10 :"; SumDigits(1, 10)
Print "1234 base 10 :"; SumDigits(1234, 10)
Print "fe   base 16 :"; SumDigits(&Hfe, 16)
Print "f0e  base 16 :"; SumDigits(&Hf0e, 16)
Print
Print "Press any key to quit the program"
Sleep


sumDigits[n, base=10] := sum[integerDigits[n, base]]


GET "libhdr"

LET sumdiv(n, d) = VALOF {
    LET m = n/d
    RESULTIS m*(m + 1)/2 * d
}

LET sum3or5(n) = sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15)

LET start() = VALOF {
    LET sum = 0
    LET n = 1

    FOR k = 1 TO 999 DO
        IF k MOD 3 = 0 | k MOD 5 = 0 THEN sum +:= k
    writef("The sum of the multiples of 3 and 5 < 1000 is %d *n", sum)

    writef("Next, the awesome power of inclusion/exclusion...*n");
    FOR i = 1 TO 10 {
        writef("%11d %d *n", n, sum3or5(n - 1))
        n *:= 10
    }

    RESULTIS 0
}


series_sum = proc (from, to: int,
                   fn: proctype (real) returns (real))
             returns (real)
    sum: real := 0.0
    for i: int in int$from_to(from, to) do
        sum := sum + fn(real$i2r(i))
    end
    return(sum)
end series_sum

one_over_k_squared = proc (k: real) returns (real)
    return(1.0 / (k * k))
end one_over_k_squared

start_up = proc ()
    po: stream := stream$primary_output()
    result: real := series_sum(1, 1000, one_over_k_squared)
    stream$putl(po, f_form(result, 1, 6))
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID. sum-of-series.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       78  N                       VALUE 1000.

       01  series-term             USAGE FLOAT-LONG.
       01  i                       PIC 9(4).

       PROCEDURE DIVISION.
           PERFORM VARYING i FROM 1 BY 1 UNTIL N < i
               COMPUTE series-term = series-term + (1 / i ** 2)
           END-PERFORM

           DISPLAY series-term

           GOBACK
           .


// File digit.go

package digit

import (
	"math/big"
	"strconv"
)

func SumString(n string, base int) (int, error) {
	i, ok := new(big.Int).SetString(n, base)
	if !ok {
		return 0, strconv.ErrSyntax
	}
	if i.Sign() < 0 {
		return 0, strconv.ErrRange
	}
	if i.BitLen() <= 64 {
		return Sum(i.Uint64(), base), nil
	}
	return SumBig(i, base), nil
}

func Sum(i uint64, base int) (sum int) {
	b64 := uint64(base)
	for ; i > 0; i /= b64 {
		sum += int(i % b64)
	}
	return
}

func SumBig(n *big.Int, base int) (sum int) {
	i := new(big.Int).Set(n)
	b := new(big.Int).SetUint64(uint64(base))
	r := new(big.Int)
	for i.BitLen() > 0 {
		i.DivMod(i, b, r)
		sum += int(r.Uint64())
	}
	return
}


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

unsigned long long sum35(unsigned long long limit)
{
    unsigned long long sum = 0;
    for (unsigned long long i = 0; i < limit; i++)
        if (!(i % 3) || !(i % 5))
            sum += i;
    return sum;
}

int main(int argc, char **argv)
{
    unsigned long long limit;

    if (argc == 2)
        limit = strtoull(argv[1], NULL, 10);
    else
        limit = 1000;

    printf("%lld\n", sum35(limit));
    return 0;
}


(loop for x from 1 to 1000 summing (expt x -2))


def digitsum = { number, radix = 10 ->
    Integer.toString(number, radix).collect { Integer.parseInt(it, radix) }.sum()
}


digsum
  :: Integral a
  => a -> a -> a
digsum base = f 0
  where
    f a 0 = a
    f a n = f (a + r) q
      where
        (q, r) = n `quotRem` base

main :: IO ()
main = print $ digsum 16 255 -- "FF": 15 + 15 = 30


using System;
using System.Collections.Generic;
using System.Numerics;

namespace RosettaCode
{
    class Program
    {
        static void Main()
        {
            List<BigInteger> candidates = new List<BigInteger>(new BigInteger[] { 1000, 100000, 10000000, 10000000000, 1000000000000000 });
            candidates.Add(BigInteger.Parse("100000000000000000000"));

            foreach (BigInteger candidate in candidates)
            {
                BigInteger c = candidate - 1;
                BigInteger answer3 = GetSumOfNumbersDivisibleByN(c, 3);
                BigInteger answer5 = GetSumOfNumbersDivisibleByN(c, 5);
                BigInteger answer15 = GetSumOfNumbersDivisibleByN(c, 15);

                Console.WriteLine("The sum of numbers divisible by 3 or 5 between 1 and {0} is {1}", c, answer3 + answer5 - answer15);
            }

            Console.ReadKey(true);
        }

        private static BigInteger GetSumOfNumbersDivisibleByN(BigInteger candidate, uint n)
        {
            BigInteger largest = candidate;
            while (largest % n > 0)
                largest--;
            BigInteger totalCount = (largest / n);
            BigInteger pairCount = totalCount / 2;
            bool unpairedNumberOnFoldLine = (totalCount % 2 == 1);
            BigInteger pairSum = largest + n;
            return pairCount * pairSum + (unpairedNumberOnFoldLine ? pairSum / 2 : 0);
        }

    }
}


import std.stdio, std.traits;

ReturnType!TF series(TF)(TF func, int end, int start=1)
pure nothrow @safe @nogc {
    typeof(return) sum = 0;
    foreach (immutable i; start .. end + 1)
        sum += func(i);
    return sum;
}

void main() {
    writeln("Sum: ", series((in int n) => 1.0L / (n ^^ 2), 1_000));
}


procedure main(a)
    write(dsum(a[1]|1234,a[2]|10))
end

procedure dsum(n,b)
    n := integer((\b|10)||"r"||n)
    sum := 0
    while sum +:= (0 < n) % b do n /:= b
    return sum
end


import java.math.BigInteger;
public class SumDigits {
    public static int sumDigits(long num) {
	return sumDigits(num, 10);
    }
    public static int sumDigits(long num, int base) {
	String s = Long.toString(num, base);
	int result = 0;
	for (int i = 0; i < s.length(); i++)
	    result += Character.digit(s.charAt(i), base);
	return result;
    }
    public static int sumDigits(BigInteger num) {
	return sumDigits(num, 10);
    }
    public static int sumDigits(BigInteger num, int base) {
	String s = num.toString(base);
	int result = 0;
	for (int i = 0; i < s.length(); i++)
	    result += Character.digit(s.charAt(i), base);
	return result;
    }

    public static void main(String[] args) {
	System.out.println(sumDigits(1));
	System.out.println(sumDigits(12345));
	System.out.println(sumDigits(123045));
	System.out.println(sumDigits(0xfe, 16));
	System.out.println(sumDigits(0xf0e, 16));
	System.out.println(sumDigits(new BigInteger("12345678901234567890")));
    }
}