text:
# Sum digits of an integer

Sum digits of an integer
You are encouraged to solve this task according to the task description, using any language you may know.

This task is to take a Natural Number in a given Base and return the sum of its digits:

`1``10` sums to ${\displaystyle 1}$;
`1234``10` sums to ${\displaystyle 10}$;
`fe``16` sums to ${\displaystyle 29}$;
`f0e``16` sums to ${\displaystyle 29}$.

Numeric constants in Ada are either decimal or written as B#Digits#. Here B is the base, written as a decimal number, and Digits is a base-B number. E.g., 30, 10#30# 2#11110#, and 16#1E# are the same number -- either written in decimal, binary or hexadecimal notation.

`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));  --  29end Sum_Digits;`
Output:
`          1         15         15        104         11         29         29`

## ALGOL 68

Works with: ALGOL 68G version Any - tested with release 2.8.win32
` # 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 ) ) ) `
Output:
```value\base base digit-sum
1\10   10         1
1234\10   10        10
fe\16   16        29
f0e\16   16        29
73\10   71         3
```

## ATS

` (* ****** ****** *)//// How to compile:// patscc -DATS_MEMALLOC_LIBC -o SumDigits SumDigits.dats//(* ****** ****** *)//#include"share/atspre_staload.hats"//(* ****** ****** *) externfun{a:t@ype}SumDigits(n: a, base: int): a implement{a}(*tmp*)SumDigits(n, base) = let//val base = gnumber_int(base)//funloop (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> (* ****** ****** *) implementmain0 () ={//val n = 1val () = println! ("SumDigits(1, 10) = ", SumDigits_int(n, 10))val n = 12345val () = println! ("SumDigits(12345, 10) = ", SumDigits_int(n, 10))val n = 123045val () = println! ("SumDigits(123045, 10) = ", SumDigits_int(n, 10))val n = 0xfeval () = println! ("SumDigits(0xfe, 16) = ", SumDigits_int(n, 16))val n = 0xf0eval () = println! ("SumDigits(0xf0e, 16) = ", SumDigits_int(n, 16))//} (* end of [main0] *) `
Output:
```SumDigits(1, 10) = 1
SumDigits(12345, 10) = 15
SumDigits(123045, 10) = 15
SumDigits(0xfe, 16) = 29
SumDigits(0xf0e, 16) = 29
```

## AutoHotkey

Translated from the C version.

`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}`
Output:
`1 15 15 29 29`

## AWK

MAWK only support base 10 numeric constants, so a conversion function is necessary.

Will sum digits in numbers from base 2 to base 16.

The output is in decimal. Output in other bases would require a function to do the conversion because MAWK's printf() does not support bases other than 10.

Other versions of AWK may not have these limitations.

`#!/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} `
Output:
``` 1
3
29
29
```

## BASIC

Works with: QBasic
Works with: PowerBASIC
Translation of: Visual Basic

Note that in order for this to work with the Windows versions of PowerBASIC, the test code needs to be with `FUNCTION PBMAIN`.

`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, 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 = outpEND 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)`
Output:
``` 1
10
11
20
0
```

See also: BBC BASIC, Run BASIC, Visual Basic

### Applesoft BASIC

`10 BASE = 1020 N\$ = "1" : GOSUB 100 : PRINT N30 N\$ = "1234" : GOSUB 100 : PRINT N40 BASE = 1650 N\$ = "FE" : GOSUB 100 : PRINT N60 N\$ = "F0E" : GOSUB 100 : PRINT N90 END 100 REM SUM DIGITS OF N\$, BASE110 IF BASE = 1 THEN N = LEN(N\$) : RETURN120 IF BASE < 2 THEN BASE = 10130 N = 0 : V\$ = LEFT\$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", BASE)140 FOR I = 1 TO LEN(N\$) : C\$ = MID\$(N\$, I, 1)150     FOR J = 1 TO LEN(V\$)160         IF C\$ <> MID\$(V\$, J, 1) THEN NEXT J : N = SQR(-1) : STOP170     N = N + J - 1180 NEXT I190 RETURN`

## BBC BASIC

This solution deliberately avoids MOD and DIV so it is not restricted to 32-bit integers.

`      *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`
Output:
```Digit sum of 1 (base 10) is 1
Digit sum of 12345 (base 10) is 15
Digit sum of 9876543210 (base 10) is 45
Digit sum of FE (base 16) is 1D (base 16)
Digit sum of F0E (base 16) is 1D (base 16)
```

## bc

`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 = 10s(1)s(1234)ibase = 16s(FE)s(F0E)`
Output:
```1
10
29
29```

## C

`#include <stdio.h> int SumDigits(unsigned long long n, const int base) {    int sum = 0;    for (; n; n /= base)    	sum += n % base;    return sum;} int main() {    printf("%d %d %d %d %d\n",        SumDigits(1, 10),        SumDigits(12345, 10),        SumDigits(123045, 10),        SumDigits(0xfe, 16),        SumDigits(0xf0e, 16) );    return 0;}`
Output:
`1 15 15 29 29`

## C#

`namespace RosettaCode.SumDigitsOfAnInteger{    using System;    using System.Collections.Generic;    using System.Linq;     internal static class Program    {        /// <summary>        ///     Enumerates the digits of a number in a given base.        /// </summary>        /// <param name="number"> The 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));            }        }    }}`
Output:
```1
15
15
29
29```

## C++

`#include <iostream>#include <cmath>int SumDigits(const unsigned long long int digits, const int BASE = 10) {    int sum = 0;    unsigned long long int x = digits;    for (int i = log(digits)/log(BASE); i>0; i--){        const double z = std::pow(BASE,i);	  const unsigned long long int t = x/z;	  sum += t;	  x -= 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;}`
Output:
`1 15 15 29 29`

### Template metaprogramming version

Tested with g++-4.6.3 (Ubuntu).

` // Template Metaprogramming version by Martin Ettl#include <iostream>#include <cmath> typedef unsigned long long int T;template <typename T, T i> void For(T &sum, T &x, const T &BASE){    const double z(std::pow(BASE,i));    const T t = x/z;    sum += t;    x -= t*z;     For<T, i-1>(sum,x,BASE);}template <> void For<T,0>(T &, T &, const T &){} template <typename T, T digits, int BASE> T SumDigits() {    T sum(0);    T x(digits);    const T end(log(digits)/log(BASE));    For<T,end>(sum,x,BASE);    return x+sum;} int main() {        std::cout << SumDigits<T, 1     , 10>()  << ' '                  << SumDigits<T, 12345 , 10>()  << ' '                  << SumDigits<T, 123045, 10>()  << ' '                  << SumDigits<T, 0xfe  , 16>()  << ' '                  << SumDigits<T, 0xf0e , 16>()  << std::endl;        return 0;} `
Output:
`1 15 15 29 29`

## Clojure

`(defn sum-digits [n base]   (let [number (if-not (string? n) (Long/toString n base) n)]    (reduce + (map #(Long/valueOf (str %) base) number))))`
Output:
```user=> (sum-digits 1 10)
1
user=> (sum-digits 1234 10)
10
user=> (sum-digits "fe" 16)
29
user=> (sum-digits "f0e" 16)
29
user=> (sum-digits 254 16)
29
user=> (sum-digits 3854 16)
29
user=> (sum-digits 16rfe 16)
29
user=> (sum-digits 16rf0e 16)
29
user=> (sum-digits "clojure" 32)
147```

## Common Lisp

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

Example:

`(loop for (number base) in '((1 10) (1234 10) (#xfe 16) (#xf0e 16))      do (format t "(~a)_~a = ~a~%" number base (sum-digits number base)))`
Output:
```(1)_10 = 1
(1234)_10 = 10
(254)_16 = 29
(3854)_16 = 29
```

## D

`import std.stdio, std.bigint; uint sumDigits(T)(T n, in uint base=10) pure nothrowin {    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;}`
Output:
```1
10
29
29
10```

## Elixir

`defmodule DS do  def sum_digits(n), do: sum_digits(n, 10)  def sum_digits(n, base) do    n |> Integer.digits(base) |> Enum.sum  endend test_cases = [{1, 10}, {1234, 10}, {0xfe, 16}, {0xf0e, 16}]for {n, base} <- test_cases, do: IO.puts(DS.sum_digits(n, base))`
Output:
```1
10
29
29
```

## Emacs Lisp

` (defun digit-sum (n)  (apply '+        (mapcar 'string-to-number                (cdr (butlast (split-string (number-to-string n) "") ))))) (insert (format "%d\n" (digit-sum 1234) )) `

Output:

```
10
```

## Erlang

` -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)). `

Example usage:

```2> sum_digits:sum_digits(1).
1
3> sum_digits:sum_digits(1234).
10
4> sum_digits:sum_digits(16#fe,16).
29
5> sum_digits:sum_digits(16#f0e,16).
29
```

## Ezhil

` # இது ஒரு எழில் தமிழ் நிரலாக்க மொழி உதாரணம் # sum of digits of a number# எண்ணிக்கையிலான இலக்கங்களின் தொகை நிரல்பாகம் எண்_கூட்டல்( எண் )  தொகை = 0  @( எண் > 0 ) வரை     d = எண்%10;     பதிப்பி "digit = ",d     எண் = (எண்-d)/10;     தொகை  = தொகை  + d  முடி  பின்கொடு தொகை முடி  பதிப்பி எண்_கூட்டல்( 1289)#20பதிப்பி எண்_கூட்டல்( 123456789)# 45 `

## F#

`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`

### or Generically

In order to complete the Digital root task I require a function which can handle numbers larger than 32 bit integers.

` //Sum Digits of An Integer - Nigel Galloway: January 31st., 2015//This code will work with any integer typelet inline sumDigits N BASE =  let rec sum(g, n) = if n < BASE then n+g else sum(g+n%BASE, n/BASE)  sum(LanguagePrimitives.GenericZero<_>,N) `
Output:
```> sumDigits 254 2;;
val it : int = 7
> sumDigits 254 10;;
val it : int = 11
> sumDigits 254 16;;
val it : int = 29
> sumDigits 254 23;;
val it : int = 12
```

so let's try it with a big integer

```> sumDigits 123456789123456789123456789123456789123456789I 10I;;
val it : System.Numerics.BigInteger = 225 {IsEven = false;
IsOne = false;
IsPowerOfTwo = false;
IsZero = false;
Sign = 1;}
```

## Factor

`: 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`
Output:
```--- Data stack:
1
10
29
29```

## Forth

This is an easy task for Forth, that has built in support for radices up to 36. You set the radix by storing the value in variable BASE.

`: sum_int 0 begin over while swap base @ /mod swap rot + repeat nip ;  2 base ! 11110 sum_int decimal  . cr10 base ! 12345 sum_int decimal  . cr16 base ! f0e   sum_int decimal  . cr`

## Fortran

Please find GNU/linux compilation instructions along with the sample output within the comments at the start of this FORTRAN 2008 source. Thank you. Review of this page shows a solution to this task with the number input as text. The solution is the sum of index positions in an ordered list of digit characters. (awk). Other solutions ignore the representations of the input, encode digits using the base, then sum the encoding. Both methods appear in this implementation.

` !-*- 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 :: reversecontains  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 antibaseend module base_mod program digit_sum  use base_mod  call still  call confusedcontains  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 process0end program digit_sum `

## Go

Handling numbers up to 2^64-1 and bases from 2 to 36 is pretty easy, larger values can be handled using the `math/big` package (but it's still limited to base<=36).

`// 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}`
`// File digit_test.go package digit import "testing" type testCase struct {	n    string	base int	dSum int} var testData = []testCase{	{"1", 10, 1},	{"1234", 10, 10},	{"fe", 16, 29},	{"f0e", 16, 29},	{"18446744073709551615", 10, 87},	{"abcdefghijklmnopqrstuvwzuz0123456789", 36, 628},} func TestSumString(t *testing.T) {	for _, tc := range testData {		ds, err := SumString(tc.n, tc.base)		if err != nil {			t.Error("test case", tc, err)			continue		}		if ds != tc.dSum {			t.Error("test case", tc, "got", ds, "expected", tc.dSum)		}	}} func TestErrors(t *testing.T) {	for _, tc := range []struct {		n    string		base int	}{		{"1234", 37},		{"0", 1},		{"1234", 4},		{"-123", 10},	} {		_, err := SumString(tc.n, tc.base)		if err == nil {			t.Error("expected error for", tc)		}		t.Log("got expected error:", err)	}}`

## Groovy

Solution:

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

Test:

`[[30, 2], [30, 10], [1, 10], [12345, 10], [123405, 10], [0xfe, 16], [0xf0e, 16]].each {    println """    Decimal value:     \${it[0]}    Radix:             \${it[1]}    Radix value:       \${Integer.toString(it[0], it[1])}    Decimal Digit Sum: \${digitsum(it[0], it[1])}    Radix Digit Sum:   \${Integer.toString(digitsum(it[0], it[1]), it[1])}    """}`
Output:
```    Decimal value:     30
Decimal Digit Sum: 4
Radix Digit Sum:   100

Decimal value:     30
Decimal Digit Sum: 3
Radix Digit Sum:   3

Decimal value:     1
Decimal Digit Sum: 1
Radix Digit Sum:   1

Decimal value:     12345
Decimal Digit Sum: 15
Radix Digit Sum:   15

Decimal value:     123405
Decimal Digit Sum: 15
Radix Digit Sum:   15

Decimal value:     254
Decimal Digit Sum: 29
Radix Digit Sum:   1d

Decimal value:     3854
Decimal Digit Sum: 29
Radix Digit Sum:   1d```

`digsum base = f 0 where	f a 0 = a	f a n = f (a+r) q where		(q,r) = n `divMod` base main = print \$ digsum 16 255 -- "FF": 15 + 15 = 30`

## Icon and Unicon

This solution works in both languages. This solution assumes the input number is expressed in the indicated base. This assumption differs from that made in some of the other solutions.

`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 sumend`

Sample runs:

```->sdi 1
1
->sdi 1234
10
->sdi fe 16
29
->sdi f0e 16
29
->sdi ff 16
30
->sdi 255 16
12
->sdi fffff 16
75
->sdi 254 16
11
->
```

## J

`digsum=: 10&\$: : (+/@(#.inv))`

Example use:

`   digsum 123410   10 digsum 25411   16 digsum 25429`

Illustration of mechanics:

`   10 #. 1 2 3 41234  10 #.inv 12341 2 3 4  10 +/ 1 2 3 410  10 +/@(#.inv) 123410`

So #.inv gives us the digits, +/ gives us the sum, and @ glues them together with +/ being a "post processor" for #.inv or, as we say in the expression: (#.inv). We need the parenthesis or inv will try to look up the inverse of +/@#. and that's not well defined.

The rest of it is about using 10 as the default left argument when no left argument is defined. A J verb has a monadic definition (for use with one argument) and a dyadic definition (for use with two arguments) and : derives a new verb where the monadic definition is used from the verb on the left and the dyadic definition is used from the verb on the right. \$: is a self reference to the top-level defined verb.

Full examples:

`   digsum 11   digsum 123410   16 digsum 16bfe29   16 digsum 16bf0e29`

Note that J implements numeric types -- J tries to ensure that the semantics of numbers match their mathematical properties. So it doesn't matter how we originally obtained a number.

`   200+54254   254254   2.54e2254   16bfe254   254b10 , 1r254b0.1  NB. 10 in base 254 , 0.1 in base 1/254254 254`

## Java

`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")));    }}`
Output:
```1
15
15
29
29
90
```

## jq

The following pipeline will have the desired effect if numbers and/or strings are presented as input:

`tostring | explode | map(tonumber - 48) | add`
For example:
` \$ jq -M 'tostring | explode | map(tonumber - 48) | add'1236"123"6`

## Julia

Using the built-in `digits` function:

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

## Lasso

`define br => '<br />\n' define sumdigits(int, base = 10) => {	fail_if(#base < 2, -1, 'Base need to be at least 2')	local(		out		= integer,		divmod	)	while(#int) => {		 #divmod = #int -> div(#base)		 #int = #divmod -> first		 #out += #divmod -> second	}	return #out} sumdigits(1)brsumdigits(12345)brsumdigits(123045)brsumdigits(0xfe, 16)brsumdigits(0xf0e, 16)`
Output:
```1
15
15
29
29```

## LiveCode

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

Example

`put sumdigits(1,10) & comma & \    sumdigits(1234,10) & comma & \    sumdigits(fe,16) & comma & \    sumdigits(f0e,16)`
Output
`1,10,29,29`

## Logo

`make "digits "0123456789abcdefghijklmnopqrstuvwxyz to digitvalue :digit   output difference find [equal? :digit item ? :digits] iseq 1 count :digits 1end to sumdigits :number [:base 10]  output reduce "sum map.se "digitvalue :numberend foreach [1 1234 fe f0e] [print (se ? "-> sumdigits ?)]`
Output:
```1 -> 1
1234 -> 10
fe -> 29
f0e -> 29```

## Lua

`function sum_digits(n, base)    sum = 0    while n > 0.5 do        m = math.floor(n / base)        digit = n - m * base        sum = sum + digit        n = m    end    return sumend print(sum_digits(1, 10))print(sum_digits(1234, 10))print(sum_digits(0xfe, 16))print(sum_digits(0xf0e, 16))`
Output:
```1
10
29
29```

## Mathematica

`Total[IntegerDigits[1234]]Total[IntegerDigits[16^^FE, 16]]`
Output:
```10
29```

## МК-61/52

`П0	<->	П1	Сx	П2	ИП1	^	ИП0	/	[x]П3	ИП0	*	-	ИП2	+	П2	ИП3	П1	x=005	ИП2	С/П`

## ML

### mLite

Left in the to_radix even though not used in the solution.

`exception :radix_out_of_range and :unknown_digit; fun to_radix (0, radix, result) = implode result           | (n, radix > 36, result) = raise :radix_out_of_range           | (n rem radix > 10, radix, result) =               to_radix (n div radix, radix,                         chr (n rem radix + ord #"a" - 10) :: result)           | (n, radix, result) =               to_radix (n div radix, radix,                         chr (n rem radix + ord #"0") :: result)           | (n, radix) = to_radix (n, radix, []);fun from_radix (s, radix) =      let val digits = explode "0123456789abcdefghijklmnopqrstuvwxyz";          val len_digits = len digits;          fun index (_, n >= radix, c) = raise :unknown_digit                  | (h :: t, n, c = h) = n                  | (_ :: t, n, c) = index (t, n + 1, c)                  | c = index (digits, 0, c)          and conv ([], radix, power, n) = n                 | (h :: t, radix, power, n) =                     conv (t, radix, power * radix, index h * power + n)                 | (s, radix) = conv (rev ` explode s, radix, 1, 0)          in            conv (s, radix)          end ;fun sumdig		([], base, n) = n	|	(h :: t, base, n) = sumdig (t, base, from_radix (implode [h], base) + n)	|	(s, base) = sumdig (explode s, base, 0) ;fun shosum (s, b) = (print "sum of digits of "; print s; print " (base "; print b; print ") = "; println ` sumdig (s, b)); shosum ("10fg",17);shosum ("deadbeef",16);shosum ("1101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",2);shosum ("thequickbrownfoxjumpsoverthelazydog",36); `

Output

```sum of digits of 10fg (base 17) = 32
sum of digits of deadbeef (base 16) = 104
sum of digits of 1101010101010101010101010101010101010101010101010101010101010101010101010101010101010101 (base 2) = 45
sum of digits of thequickbrownfoxjumpsoverthelazydog (base 36) = 788```

## NetRexx

### Strings

Processes data as text from the command line. Provides a representative sample if no input is supplied:

`/* NetRexx */options replace format comments java crossref symbols nobinary parse arg inputinputs = ['1234', '01234', '0xfe', '0xf0e', '0', '00', '0,2' '1', '070', '77, 8' '0xf0e, 10', '070, 16', '0xf0e, 36', '000999ABCXYZ, 36', 'ff, 16', 'f, 10', 'z, 37'] -- test dataif input.length() > 0 then inputs = [input] -- replace test data with user inputloop i_ = 0 to inputs.length - 1  in = inputs[i_]  parse in val . ',' base .  dSum = sumDigits(val, base)  say 'Sum of digits for integer "'val'" for a given base of "'base'":' dSum'\-'  -- Carry the exercise to it's logical conclusion and sum the results to give a single digit in range 0-9  loop while dSum.length() > 1 & dSum.datatype('n')    dSum = sumDigits(dSum, 10)    say ',' dSum'\-'    end  say  end i_ -- Sum digits of an integermethod sumDigits(val = Rexx, base = Rexx '') public static returns Rexx   rVal = 0  parse normalizeValue(val, base) val base .  loop label digs for val.length()    -- loop to extract digits from input and sum them    parse val dv +1 val    do      rVal = rVal + Integer.valueOf(dv.toString(), base).intValue()    catch ex = NumberFormatException      rVal = 'NumberFormatException:' ex.getMessage()      leave digs    end    end digs  return rVal -- Clean up the input, normalize the data and determine which base to usemethod normalizeValue(inV = Rexx, base = Rexx '') private static returns Rexx  inV = inV.strip('l')  base = base.strip()  parse inV xpref +2 . -         =0 opref +1 . -         =0 . '0x' xval . ',' . -         =0 . '0'  oval . ',' . -         =0 dval .   select    when xpref = '0x' & base.length() = 0 then do      -- value starts with '0x' and no base supplied.  Assign hex as base      inval = xval      base = 16      end    when opref = '0'  & base.length() = 0 then do      -- value starts with '0' and no base supplied.  Assign octal as base      inval = oval      base = 8      end    otherwise do      inval = dval      end    end  if base.length() = 0 then base = 10 -- base not set.  Assign decimal as base  if inval.length() <= 0 then inval = 0 -- boundary condition.  Invalid input or a single zero  rVal = inval base   return rVal `
Output:
```Sum of digits for integer "1234" for a given base of "": 10, 1
Sum of digits for integer "01234" for a given base of "": 10, 1
Sum of digits for integer "0xfe" for a given base of "": 29, 11, 2
Sum of digits for integer "0xf0e" for a given base of "": 29, 11, 2
Sum of digits for integer "0" for a given base of "": 0
Sum of digits for integer "00" for a given base of "": 0
Sum of digits for integer "0" for a given base of "2": 0
Sum of digits for integer "070" for a given base of "": 7
Sum of digits for integer "77" for a given base of "8": 14, 5
Sum of digits for integer "070" for a given base of "16": 7
Sum of digits for integer "0xf0e" for a given base of "36": 62, 8
Sum of digits for integer "000999ABCXYZ" for a given base of "36": 162, 9
Sum of digits for integer "ff" for a given base of "16": 30, 3
Sum of digits for integer "f" for a given base of "10": NumberFormatException: For input string: "f"
Sum of digits for integer "z" for a given base of "37": NumberFormatException: radix 37 greater than Character.MAX_RADIX
```

### Type int

Processes sample data as int arrays:

`/* NetRexx */options replace format comments java crossref symbols binary inputs = [[int 1234, 10], [octal('01234'), 8], [0xfe, 16], [0xf0e,16], [8b0, 2], [16b10101100, 2], [octal('077'), 8]] -- test dataloop i_ = 0 to inputs.length - 1  in = inputs[i_, 0]  ib = inputs[i_, 1]  dSum = sumDigits(in, ib)  say 'Sum of digits for integer "'Integer.toString(in, ib)'" for a given base of "'ib'":' dSum'\-'  -- Carry the exercise to it's logical conclusion and sum the results to give a single digit in range 0-9  loop while dSum.length() > 1 & dSum.datatype('n')    dSum = sumDigits(dSum, 10)    say ',' dSum'\-'    end  say  end i_ -- Sum digits of an integermethod sumDigits(val = int, base = int 10) public static returns Rexx  rVal = Rexx 0  sVal = Rexx(Integer.toString(val, base))  loop label digs for sVal.length()    -- loop to extract digits from input and sum them    parse sVal dv +1 sVal    do      rVal = rVal + Integer.valueOf(dv.toString(), base).intValue()    catch ex = NumberFormatException      rVal = 'NumberFormatException:' ex.getMessage()      leave digs    end    end digs  return rVal -- if there's a way to insert octal constants into an int in NetRexx I don't remember itmethod octal(oVal = String) private constant returns int signals NumberFormatException  iVal = Integer.valueOf(oVal, 8).intValue()  return iVal `
Output:
```Sum of digits for integer "1234" for a given base of "10": 10, 1
Sum of digits for integer "1234" for a given base of "8": 10, 1
Sum of digits for integer "fe" for a given base of "16": 29, 11, 2
Sum of digits for integer "f0e" for a given base of "16": 29, 11, 2
Sum of digits for integer "0" for a given base of "2": 0
Sum of digits for integer "10101100" for a given base of "2": 4
Sum of digits for integer "77" for a given base of "8": 14, 5
```

## Nim

`proc sumdigits(n, base: Natural): Natural =  var n = n  while n > 0:    result += n mod base    n = n div base echo sumDigits(1, 10)echo sumDigits(12345, 10)echo sumDigits(123045, 10)echo sumDigits(0xfe, 16)echo sumDigits(0xf0e, 16)`
Output:
```1
15
15
29
29```

## Oberon-2

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

## OCaml

`let sum_digits ~digits ~base =  let rec aux sum x =    if x <= 0 then sum else    aux (sum + x mod base) (x / base)  in  aux 0 digits let () =  Printf.printf "%d %d %d %d %d\n"    (sum_digits 1 10)    (sum_digits 12345 10)    (sum_digits 123045 10)    (sum_digits 0xfe 16)    (sum_digits 0xf0e 16)`
Output:
`1 15 15 29 29`

## Oforth

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

Usage :

`sumDigits(1, 10) printlnsumDigits(1234, 10) printlnsumDigits(0xfe, 16) printlnsumDigits(0xf0e, 16) println`
Output:
```1
10
29
29
```

## PARI/GP

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

Also the built-in `sumdigits` can be used for base 10.

## Pascal

`Program SumOFDigits; function SumOfDigitBase(n:UInt64;base:LongWord): LongWord;var  tmp: Uint64;  digit,sum : LongWord;Begin  digit := 0;  sum   := 0;  While n > 0 do  Begin    tmp := n div base;    digit := n-base*tmp;    n := tmp;    inc(sum,digit);  end;  SumOfDigitBase := sum;  end;Begin  writeln('   1 sums to ', SumOfDigitBase(1,10));   writeln('1234 sums to ', SumOfDigitBase(1234,10));    writeln(' \$FE sums to ', SumOfDigitBase(\$FE,16));   writeln('\$FOE sums to ', SumOfDigitBase(\$F0E,16));      writeln('18446744073709551615 sums to ', SumOfDigitBase(High(Uint64),10));   end.`
output
```   1 sums to 1
1234 sums to 10
\$FE sums to 29
\$FOE sums to 29
18446744073709551615 sums to 87```

## Perl

`#!/usr/bin/perluse strict ;use warnings ; #whatever the number base, a number stands for itself, and the letters start#at number 10 ! sub sumdigits {   my \$number = shift ;   my \$hashref = shift ;   my \$sum = 0 ;   map { if ( /\d/ ) { \$sum += \$_ } else { \$sum += \${\$hashref}{ \$_ } } }       split( // , \$number ) ;   return \$sum ;} my %lettervals ;my \$base = 10 ;for my \$letter ( 'a'..'z' ) {   \$lettervals{ \$letter } = \$base++ ;}map { print "\$_ sums to " . sumdigits( \$_ , \%lettervals) . " !\n" }    ( 1 , 1234 , 'fe' , 'f0e' ) ; `
Output:
```1 sums to 1 !
1234 sums to 10 !
fe sums to 29 !
f0e sums to 29 !
```

## Perl 6

This will handle input numbers in any base from 2 to 36. The results are in base 10.

`say Σ \$_ for <1 1234 1020304 fe f0e DEADBEEF>; sub Σ { [+] \$^n.comb.map: { :36(\$_) } }`
Output:
```1
10
10
29
29
104```

## PHP

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

## PicoLisp

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

Test:

`: (sumDigits 1 10)-> 1 : (sumDigits 1234 10)-> 10 : (sumDigits (hex "fe") 16)-> 29 : (sumDigits (hex "f0e") 16)-> 29`

## PL/I

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

results:

```5c7e
SD=      38;
10111000001
SD=       5;
```

## PowerShell

`function Get-DigitalSum (\$n){    if (\$n -lt 10) {\$n}    else {        (\$n % 10) + (Get-DigitalSum ([math]::Floor(\$n / 10)))    }}`

## Python

`def toBaseX(num, base):    output = []    while num:        num, rem = divmod(num, base)        output.append(rem)    return output def sumDigits(num, base=10):    if base < 2:        print "Error: Base must be at least 2"        return    return sum(toBaseX(num, base)) print sumDigits(1)print sumDigits(12345)print sumDigits(123045)print sumDigits(0xfe, 16)print sumDigits(0xf0e, 16)`
Output:
```1
15
15
29
29
```

The following does no error checking and requires non-base 10 numbers passed as string arguments:

` def sumDigits(num, base=10):    return sum([int(x, base) for x in list(str(num))]) print sumDigits(1)print sumDigits(12345)print sumDigits(123045)print sumDigits('fe', 16)print sumDigits("f0e", 16)`

Each digit is base converted as it's summed.

## R

Translation of: Python
`change.base <- function(n, base){  ret <- integer(as.integer(logb(x=n, base=base))+1L)   for (i in 1:length(ret))  {    ret[i] <- n %% base    n <- n %/% base   }   return(ret)} sum.digits <- function(n, base=10){  if (base < 2)    stop("base must be at least 2")   return(sum(change.base(n=n, base=base)))} sum.digits(1)sum.digits(12345)sum.digits(123045)sum.digits(0xfe, 16)sum.digits(0xf0e, 16)`

## Racket

`#lang racket(define (sum-of-digits n base (sum 0))  (if (= n 0)      sum      (sum-of-digits (quotient n base)                     base                     (+ (remainder n base) sum)))) (for-each (lambda (number-base-pair)   (define number (car number-base-pair))   (define base (cadr number-base-pair))   (displayln (format "(~a)_~a = ~a" number base (sum-of-digits number base)))) '((1 10) (1234 10) (#xfe 16) (#xf0e 16)))   ;  outputs:;    (1)_10 = 1;    (1234)_10 = 10;    (254)_16 = 29;    (3854)_16 = 29`

## REXX

### version 1

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

### version 2

This REXX version allows:

• leading signs   (+ -)
• decimal points
• leading and/or trailing whitespace
• numbers may be in mixed case
• numbers may include commas   (,)
• numbers may be expressed up to base 36
• numbers may be any length (size)
`/*REXX pgm sums the digits of natural numbers in any base up to base 36.*/parse arg z                            /*get optional #s or use default.*/if z=''  then z='1 1234 fe f0e +F0E -666.00 11111112222222333333344444449'     do j=1  for words(z);     _=word(z,j)     say right(sumDigs(_),9) ' is the sum of the digits for the number ' _     end   /*j*/exit                                   /*stick a fork in it, we're done.*//*──────────────────────────────────SUMDIGS subroutine──────────────────*/sumDigs: procedure;    arg x;        @=123456789ABCDEFGHIJKLMNOPQRSTUVWXYZs=0;                do k=1  for length(x);        s=s+pos(substr(x,k,1),@)                    end   /*k*/return s`
Output:
when using the default input
```        1  is the sum of the digits for the number  1
10  is the sum of the digits for the number  1234
29  is the sum of the digits for the number  fe
29  is the sum of the digits for the number  f0e
29  is the sum of the digits for the number  +F0E
18  is the sum of the digits for the number  -666.00
79  is the sum of the digits for the number  11111112222222333333344444449
```

### version 3

This REXX version is an optimized version limited to base ten integers only for fast decomposing of a decimal number's numerals.

The function makes use of REXX's   parse   statement

`/*REXX program sums the decimal digits of integers expressed in base ten*/parse arg z                            /*get optional #s or use default.*/if z=''  then z=copies(7, 108)         /*let's generate a pretty huge #.*/numeric digits 1+max(length(z))        /*enable use of gigantic numbers.*/      do j=1  for words(z);     _=abs(word(z,j))   /*ignore sign, if any.*/     say sumDigs(_)      ' is the sum of the digits for the number '  _     end   /*j*/exit                                   /*stick a fork in it, we're done.*//*──────────────────────────────────SUMDIGS subroutine──────────────────*/sumDigs: procedure;  parse arg N 1 s 2 ?    /*use first dig for S (sum),*/                 do  while ?\=='';  parse var ? _ 2 ?;  s=s+_;  end  /*k*/return s`

output when using the default input:

```756  is the sum of the digits for the number  777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777
```

## Ruby

`>> def sumDigits(num, base = 10)>>     num.to_s(base).split(//).inject(0) {|z, x| z + x.to_i(base)}>> end=> nil>> sumDigits(1)=> 1>> sumDigits(12345)=> 15>> sumDigits(123045)=> 15>> sumDigits(0xfe, 16)=> 29>> sumDigits(0xf0e, 16)=> 29 `

## Run BASIC

 This example is incorrect. It only handles base 10, but should be able to handle multiple and/or arbitrary bases. Please fix the code and remove this message.

`input "Gimme a number:";n print "Sum of digits :";n;" is ";sum(n)endfunction sum(n)n\$ = str\$(n)for i = 1 to len(n\$)  sum = sum + val(mid\$(n\$,i,1))next iend function`
```Gimme a number:?123456789
Sum of digits :123456789 is 45```

## Scala

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

Test:

`sumDigits(0)                                // => 0sumDigits(0, 2)                             // => 0sumDigits(0, 16)                            // => 0sumDigits("00", 2)                          // => 0sumDigits("00", 10)                         // => 0sumDigits("00", 16)                         // => 0sumDigits(1234)                             // => 10sumDigits(0xfe)                             // => 11sumDigits(0xfe, 16)                         // => 29sumDigits(0xf0e, 16)                        // => 29sumDigits(077)                              // => 9sumDigits(077, 8)                           // => 14sumDigits("077", 8)                         // => 14sumDigits("077", 10)                        // => 14sumDigits("077", 16)                        // => 14sumDigits("0xf0e", 36)                      // => 62sumDigits("000999ABCXYZ", 36)               // => 162sumDigits(BigInt("12345678901234567890"))   // => 90sumDigits("12345678901234567890", 10)       // => 90`

## Seed7

`\$ include "seed7_05.s7i"; const func integer: sumDigits (in var integer: num, in integer: base) is func  result     var integer: sum is 0;  begin    while num > 0 do      sum +:= num rem base;      num := num div base;    end while;  end func; const proc: main is func  begin    writeln(sumDigits(1,      10));    writeln(sumDigits(12345,  10));    writeln(sumDigits(123045, 10));    writeln(sumDigits(123045, 50));    writeln(sumDigits(16#fe,  10));    writeln(sumDigits(16#fe,  16));    writeln(sumDigits(16#f0e, 16));  end func;`
Output:
```1
15
15
104
11
29
29
```

## Sidef

Translation of: Perl 6
`func Σ(String str, base=36) {    str.chars.map{ Num(_, base) }.sum} <1 1234 1020304 fe f0e DEADBEEF>.each { |n|    say "Σ(#{n}) = #{Σ(n)}"}`
Output:
```Σ(1) = 1
Σ(1234) = 10
Σ(1020304) = 10
Σ(fe) = 29
Σ(f0e) = 29
```

## Swift

Works with: Swift version 1.2
` let number = 1234let base   = 10 println(number.toString(base: base).characters    .map { char in String(char).toInt(base: 10) }    .reduce(0, combine: +)) `
Output:
```10
```
Works with: Swift version 2.0
` let number = 0xfelet base   = 16 // Except toString which is from ContestKit everything // else used here is defined in Swift Standard Libraryprint(number.toString(base: base).characters    .map { char in Int(String(char), radix: base)! }    .reduce(0, combine: +)) `
Output:
```29
```

## Tcl

Supporting arbitrary bases makes this primarily a string operation.

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

Demonstrating:

`puts [sumDigits 1]puts [sumDigits 12345]puts [sumDigits 123045]puts [sumDigits fe 16]puts [sumDigits f0e 16]puts [sumDigits 000999ABCXYZ 36]`
Output:
```1
15
15
29
29
162
```

## Visual Basic

This version checks that only valid digits for the indicated base are passed in, exiting otherwise.

`Function sumDigits(num As Variant, base As Long) As Long    'can handle up to base 36    Dim outp As Long    Dim validNums As String, tmp As Variant, x As Long, lennum As Long    'ensure num contains only valid characters    validNums = Left\$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", base)    lennum = Len(num)    For L0 = lennum To 1 Step -1        x = InStr(validNums, Mid\$(num, L0, 1)) - 1        If -1 = x Then Exit Function        tmp = tmp + (x * (base ^ (lennum - L0)))    Next    While tmp        outp = outp + (tmp Mod base)        tmp = tmp \ base    Wend    sumDigits = outpEnd Function Sub tester()    Debug.Print sumDigits(1, 10)    Debug.Print sumDigits(1234, 10)    Debug.Print sumDigits(&HFE, 16)    Debug.Print sumDigits(&HF0E, 16)    Debug.Print sumDigits("2", 2)End Sub`
Output:
(in the debug window):
``` 1
10
11
20
0
```

## XPL0

`code    ChOut=8, CrLf=9, IntOut=11; func    SumDigits(N, Base);int     N, Base, Sum;[Sum:= 0;repeat  N:= N/Base;        Sum:= Sum + rem(0);until   N=0;return Sum;]; [IntOut(0, SumDigits(1,      10));  ChOut(0, ^ ); IntOut(0, SumDigits(12345,  10));  ChOut(0, ^ ); IntOut(0, SumDigits(123045, 10));  ChOut(0, ^ ); IntOut(0, SumDigits(\$FE,    10));  ChOut(0, ^ ); IntOut(0, SumDigits(\$FE,    16));  ChOut(0, ^ ); IntOut(0, SumDigits(\$F0E,   16));  CrLf(0);]`
Output:
```1 15 15 11 29 29
```

## zkl

`fcn sum(n,b){n.toString(b).split("").apply("toInt",b).sum()}`

Convert the int into a string in the proper base, blow it apart into a list of digits, convert each character back into a int and add it up.

Output:
```sum(1,10);     //--> 1
sum(1234,10);  //--> 10
sum(0xfe,16);  //--> 29
sum(0xf0e,16); //--> 29
sum(0b1101,2); //--> 3
```


text:
+0

# Trying to settle a mental conflict

0
203
9

So, I'm trying to solve this: $$\begin{pmatrix} 4\\ 3 \end{pmatrix} (2x-1)=-12$$

Do I multiply both sides by the recriprical of 4/3 or do I distribute first?

Thanks!

Oct 13, 2018

#1
+1

Multiply both sides by 3/4 to get 2x-1=-9. Add 1 from both sides to get 2x=-8. Dividing both sides by 2 you get x as -4.

Oct 13, 2018
#2
+324
0

Its [4!/3!(4-3)!](2x-1)=-12 <=>

<=> 24/6(2x-1)=-12 <=>

<=> 4(2x-1)=-12 <=>

<=> 8x-4=-12 <=>

<=> 8x=-8 so x=-1

I hope to helped you!

Oct 13, 2018
#3
0

Did you mean that as 4/3 or 4 choose 3

Oct 13, 2018
#4
0

The 1st guest who answered was correct, the solution is $$x=-4$$ (I checked). Thanks for the quick help!

Oct 13, 2018
#5
+324
0

Oh im sorry i understand 4 choose 3 because you write it like this :( Im sorry !

Dimitristhym  Oct 13, 2018
edited by Dimitristhym  Oct 13, 2018
#6
0

Thats OK, for whatever reason LaTeX does NOT have an option for fractions, so I had to make-do with what looked like a fraction :)

Guest Oct 13, 2018
#7
+324
0

Ok I don't know this!

Dimitristhym  Oct 13, 2018
#8
+2

No hard feelings dude

Guest Oct 13, 2018
#9
+72
0

At least you learnt it now, but good explanation still

Oct 13, 2018

format: plain


text:
mersenneforum.org Untested Sierp conjectures sorted by conjecture
 Register FAQ Search Today's Posts Mark Forums Read

 2010-01-13, 14:14 #1 rogue     "Mark" Apr 2003 Between here and the 146138 Posts Untested Sierp conjectures sorted by conjecture Here is a list of all Sierpinski conjectures which have not been tested, ordered by ck. I figured that people who are new to the search can pick bases from this list with low k to get their feet wet. Code: base conjectured k 1015 12079606 1008 12730554 585 13929512 541 15253776 865 15460266 586 21262902 715 21508102 346 22248598 963 23276986 630 24015859 777 24088826 358 27478218 700 36945505 801 45030296 546 45119296 925 59162602 756 67836285 891 80364072 325 82786558 1020 95696289 760 113906481 141 129697332 796 137085595 210 147840103 906 161291811 271 168541962 124 173559406 876 258073912 195 289401986 85 346334170 345 356851424 120 374876369 690 395800653 175 606727296 966 924230558 399 2525403854 415 3088787196 435 3699251266 71 5917678826 921 10596584690 127 11254645362 156 18406311208 826 19730748315 981 50234474650 960 197938246042 661 1185028551412 946 1524340829428 799 1864613598304 511 3876595974396 910 4989054506113 855 7954937545864 280 82035074042274 Last fiddled with by gd_barnes on 2021-10-10 at 17:20 Reason: update status
2010-01-13, 14:39   #2
Mini-Geek
Account Deleted

"Tim Sorbera"
Aug 2006
San Antonio, TX USA

4,271 Posts

Quote:
 Originally Posted by rogue Code:  839 4 854 4 139 6
These have been tested and proven according to http://www.noprimeleftbehind.net/cru...onjectures.htm
I haven't checked many others.
How did you make this list that those wouldn't be excluded? Or was it just a mistake?

2010-01-13, 15:57   #3
rogue

"Mark"
Apr 2003
Between here and the

653910 Posts

Quote:
 Originally Posted by Mini-Geek These have been tested and proven according to http://www.noprimeleftbehind.net/cru...onjectures.htm I haven't checked many others. How did you make this list that those wouldn't be excluded? Or was it just a mistake?
Most likely an edit error on my part. I started with a spreadsheet listing the conjectures for bases <= 1024, then removed rows from the linked page. I wouldn't be surprised if my eyes got a little buggy in the process.

2010-01-13, 18:49   #4
Mini-Geek
Account Deleted

"Tim Sorbera"
Aug 2006
San Antonio, TX USA

10AF16 Posts

Quote:
 Originally Posted by rogue Most likely an edit error on my part. I started with a spreadsheet listing the conjectures for bases <= 1024, then removed rows from the linked page. I wouldn't be surprised if my eyes got a little buggy in the process.
You did it manually? Hmm...that's pretty prone to error, especially over ~2000 lines. I'll do it automated, and attach the results...
Done. (It doesn't have the nice-looking number of spaces like your list did, just a single space between each one. We'd probably want it looking like yours did before replacing it in the posts here.) For the record (so everyone else and I know how to do it in the future), here's how I did it:

get the list of conjectures, sorted by k then b in the format "b k" in one file, and
the list of bases that have been worked (from CRUS site) in another file (same format and sorting),
run "diff sierp-conjectures.csv sierp-worked.csv > sierp-diff.txt" (diff from cygwin/unix), with the two file names plugged in correctly
find/replace to remove all "> " from sierp-diff.txt
import sierp-diff.txt into OOo calc, splitting on 'd' and ',' (this will make almost all extraneous lines have more than one column, allowing us to get just the part we want)
sort by column B then A
remove all lines we don't want (which will be grouped together due to previous sorting)
now split the remaining columns on a space, sort by column B (the conj. k) then A (the base), and save as a .csv using a space to separate the lines
repeat for the other side (Riesel/Sierp)

Tada! Yeah, it's quite a bit, but it practically eliminates user error. And I'm sure it's gotta be WAY faster than going through the list of bases that have been worked manually. I found this many discrepancies between our lists: (all are ones that you included but I didn't, unless otherwise noted; all likely due to human error; someone might want to check these discrepancies from the original files and pages to be 100% sure which of us made the mistake)
Riesel: 5 diffs
Code:
 142        12
137        22
200        68
298       116
241     15918
Sierp: 13 diffs
Code:
 839        4
854        4
139        6
146        8
142       12
129       14
110       38
122       40
962 106 (on my list only)
961     1000
138     2781
143     7628
211    20238
Attached Files
 diffs.zip (6.6 KB, 332 views)

Last fiddled with by Mini-Geek on 2010-01-13 at 18:50

 2010-01-13, 20:33 #5 rogue     "Mark" Apr 2003 Between here and the 13×503 Posts That's great! I didn't think strongly about an automated way of doing it, but that clearly is an easier way to do what I tried to do. Now if Gary would go and update the first and second posts in these threads...
 2010-01-13, 21:52 #6 MyDogBuster     May 2008 Wilmington, DE B2416 Posts Tim, Now if there was a way to automate that, I'm sure Gary or Max could run that stuff at least once a week or so. Nice job by the way. Those lists are nice, but Gary will want automation or they probably won't be maintained.
2010-01-13, 22:39   #7
Mini-Geek
Account Deleted

"Tim Sorbera"
Aug 2006
San Antonio, TX USA

10AF16 Posts

Quote:
 Originally Posted by MyDogBuster Tim, Now if there was a way to automate that, I'm sure Gary or Max could run that stuff at least once a week or so. Nice job by the way. Those lists are nice, but Gary will want automation or they probably won't be maintained.
Yeah...reminds me of the top 5000 change list over at NPLB. Automating it could be possible, but is probably too much trouble to be worth it. It's not that there's anything that couldn't be automated fairly easily. It's just that putting it all together could be pretty tiresome.
If anyone's interested, it would probably be a good starting point to make a Perl script that takes the two sorted lists and outputs the difference directly in the format we want. I could see this being far easier than my method (and done entirely within a simple perl script, instead of the convoluted back-and-forth going on now involving multiple programs). One of the lists is fixed (i.e. the list of conjectures will almost never change) after it's prepared once, so we wouldn't need to consider that. Then the only other things you need are an automated way to get the sorted list of worked k's (this might be the hard part; in my method I copy/paste it from Firefox into OOo calc, a script would likely have to look at the HTML itself) and to do something with the output automatically (should be pretty easy, assuming it's being run as a cron job on the server where the result's hosted).

Last fiddled with by Mini-Geek on 2010-01-13 at 22:49

 2010-01-13, 23:41 #8 gd_barnes     May 2007 Kansas; USA 10,597 Posts Thanks again for your tireless efforts guys. I'll correct the postings later tonight.
 2010-01-14, 08:05 #9 gd_barnes     May 2007 Kansas; USA 10,597 Posts After thinking about this for a bit and after adding and updating about 10-15 new and already-tested bases on the web pages, I realized that it's going to add yet another step to the updates to manually update the 1st two posts in these two threads. It would be very difficult to keep them constantly in sync, especially as multiple small bases are done. If anyone can automate this and post an updated list every few days based on testing shown on the web pages, I'll update the posts. If we don't automate it, I might suggest something: List ALL bases sorted by conjecture and show if each base is proven or not. That would be a fairly quick one-time thing and it would be fairly easy to manually keep such a post updated whenver a conjecture becomes proven. "Untested Sierpinski conjectures with sorted by k" seemed a little confusing as to what this is so I changed the 2 thread names slightly. Gary
2010-01-14, 08:14   #10
gd_barnes

May 2007
Kansas; USA

245458 Posts

Attached is something that I did a long time back. All Sierp conjectures sorted by size, that is conjectured-k.

I just put Robert's Sierp conjectures text file into a spreadsheet and quickly used formulas to eliminate the period, cover, and blank lines, and split out the base and conjecture into separate cells. I then sorted it. So it is a virtual guarantee that the list is all there and sorted correctly.

Perhaps someone can do something a little more with this.
Attached Files
 Sierpinski conjectures by size.txt (13.5 KB, 508 views)

2010-01-14, 16:08   #11
Mini-Geek
Account Deleted

"Tim Sorbera"
Aug 2006
San Antonio, TX USA

4,271 Posts

Quote:
 Originally Posted by Mini-Geek If anyone's interested, it would probably be a good starting point to make a Perl script that takes the two sorted lists and outputs the difference directly in the format we want. I could see this being far easier than my method (and done entirely within a simple perl script, instead of the convoluted back-and-forth going on now involving multiple programs).
I've made this as a Java program, (attached is a .jar of it, along with the source code, uncommented, and a readme) so the whole process is now pretty fast, but still requires the semi-manual step of getting the info from the web page into the format we need. Fortunately it's really not too hard (or long, or involved) to do that. I've tested it and its output matches up exactly with my other method.
I think it's easy enough now to not be too hard to regularly keep up to date (be it you doing it yourself or you having me, or someone else, do it after you update the pages).
Just in case you didn't know: you can double click a .jar to run it easily.

I'll attach some updated lists in the next post. (since I can only have one attachment per post and don't want it in the same as the Java script) There are a few updates for Riesel and none for Sierp.
Attached Files
 unworked-script.zip (3.3 KB, 364 views)

Last fiddled with by Mini-Geek on 2010-01-14 at 16:20

 Similar Threads Thread Thread Starter Forum Replies Last Post rogue Conjectures 'R Us 36 2018-01-03 19:53 ONeil Information & Answers 4 2017-12-23 05:30 rogue Conjectures 'R Us 109 2017-04-29 01:28 moo Lone Mersenne Hunters 0 2005-03-24 22:38 wirthi Math 10 2003-10-05 13:02

All times are UTC. The time now is 21:23.

Thu Jan 27 21:23:01 UTC 2022 up 188 days, 15:52, 2 users, load averages: 1.66, 2.00, 2.37


text:
Free Version
Easy

Equation Procedure

APCSP-KSMEXK

Use the following code segment to answer this question.

PROCEDURE equation (a, b, c)
{
x ← a \* b
y ← a - c
z ← x/y
RETURN (z)
}

What would be the output of the equation procedure when $a$ is 9, $b$ is 10, and $c$ is 4?

A

18

B

72

C

-72

D

360


text:
# How do you find the standard deviation of 3, 7, 4, 6, and 5?

Dec 19, 2016

The standard deviation is $\sigma = \sqrt{2} \approx 1.41$

#### Explanation:

The standard deviation of a data set is given as:

## $\sigma = \sqrt{\frac{1}{N} \times {\Sigma}_{i = 1}^{N} {\left({x}_{i} - \overline{x}\right)}^{2}}$

where:
$N$- number of data;
$\overline{x}$ - mean value;
${x}_{i}$ - data in data set

To calculate the deviation we can use the following algorythm:

1. Calculate mean $\overline{x}$
2. Calculate ${\left({x}_{i} - \overline{x}\right)}^{2}$ for all $i$
3. Add all values calculated in $2$.
4. Divide the sum by $N$
5. Get square root to calculate the deviation.

Here we have:

1. $\overline{x} = \frac{3 + 4 + 5 + 6 + 7}{5} = \frac{25}{5} = 5$
2. ${\left(3 - 5\right)}^{2} = {\left(- 2\right)}^{2} = 4$
${\left(4 - 5\right)}^{2} = {\left(- 1\right)}^{2} = 1$
${\left(5 - 5\right)}^{2} = 0$
${\left(6 - 5\right)}^{2} = {1}^{2} = 1$
${\left(7 - 5\right)}^{2} = {2}^{2} = 4$
3. Sum is $4 + 1 + 0 + 1 + 4 = 10$
4. $10 \div 5 = 2$
5. $\sigma = \sqrt{2} \approx 1.41$


text:
# Problem: Draw the organic product of the following reaction. If no reaction occurs, write "No Reaction." Indicate stereochemistry where appropriate. Assume the reaction undergoes an aqueous acidic workup and neutralization.

###### FREE Expert Solution
95% (235 ratings)
###### Problem Details

Draw the organic product of the following reaction. If no reaction occurs, write "No Reaction." Indicate stereochemistry where appropriate. Assume the reaction undergoes an aqueous acidic workup and neutralization.


text:
Corpus ID: 119617667

# On the homotopy fibre of the inclusion map F\_n(X) $\rightarrow$ $\prod$\_1^n X for some orbit spaces X

@article{Golasiski2016OnTH,
title={On the homotopy fibre of the inclusion map F\_n(X) \$\rightarrow\$ \$\prod\$\_1^n X for some orbit spaces X},
author={M. Golasiński and D. Gonccalves and John Guaschi},
journal={arXiv: Geometric Topology},
year={2016}
}
• Published 2016
• Mathematics
• arXiv: Geometric Topology
• Under certain conditions, we describe the homotopy type of the homo-topy fibre of the inclusion map F\_n(X) $\rightarrow$ $\prod$\_1^n X for the n-th configuration space F\_n(X) of a topological manifold X without boundary such that dim(X) $\ge$ 3. We then apply our results to the cases where either the universal covering of X is contractible or X is an orbit space S^k/G of a tame, free action of a Lie group G on the k-sphere S^k. If the group G is finite and k is odd, we give a full… CONTINUE READING

#### References

SHOWING 1-10 OF 22 REFERENCES


text:
# bayesian survival analysis in r December 2, 2020 – Posted in: Uncategorized

Active 3 years, 5 months ago. I. 07/26/2020 ∙ by Denise Rava, et al. re... We discuss causal mediation analyses for survival data and propose a new... Multilevel mixed effects parametric survival analysis, pammtools: Piece-wise exponential Additive Mixed Modeling tools, The Multiplicative Mixed Model with the mumm R package as a General and ∙ re... It only takes a minute to sign up. BACCO is an R bundle for Bayesian analysis of random functions. This may be in part due to a relative A Bayesian Proportional-Hazards Model In Survival Analysis Stanley Sawyer — Washington University — August 24, 2004 1. There are two packages that can be used to interface R with WinBUGS . A more comprehensive treatment of Bayesian survival analysis can be found in Ibrahim, Chen, and Sinha . ∙ 0 ∙ share Survival data is encountered in a range of … share | improve this question | follow | edited Sep 16 '18 at 0:02. The Bayesian Learning for Neural Networks (BLNN) package coalesces the predictive power of neural networks with a breadth of Bayesian sampling techniques for the first time in R. BLNN offers users Hamiltonian Monte Carlo (HMC) and No-U-Turn (NUTS) sampling algorithms with dual averaging for posterior weight generation. Why did the scene cut away without showing Ocean's reply? tr... Bayesian survival analysis. To subscribe to this RSS feed, copy and paste this URL into your RSS reader. ∙ of Bayesian survival models. share, This article introduces the pammtools package, which facilitates data data can provide a number of benefits, they are less widely used than classical Is there a way to notate the repeat of a larger section that itself has repeats in it? 05/12/2020 ∙ by Danilo Alvares, et al. Bayesian data analysis in R? (GLMMs), generalised additive models (GAMs) and more. Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. 0 Survival analysis is a branch of statistics for analyzing the expected duration of time until one or more events happen, such as death in biological organisms and failure in mechanical systems. But if you scratch the surface there is a lot of Bayesian jargon! BMA: Bayesian Model Averaging . ∙ In the R example, the authors have included a vector "s" which was used to initially simulate the survival times data in their example as well as the predictors. 09/19/2017 ∙ by Michael J. Crowther, et al. share, We discuss causal mediation analyses for survival data and propose a new... 08/29/2019 ∙ by Matthew W. Wheeler, et al. Ubuntu 20.04: Why does turning off "wi-fi can be turned off to save power" turn my wi-fi off? Making statements based on opinion; back them up with references or personal experience. I'm not sure what this "s" is. I am going through R's function indeptCoxph in the spBayesSurv package which fits a bayesian Cox model. R is one of the main tools to perform this sort of analysis thanks to the survival package. Why does Taproot require a new address format? their model using customary R formula syntax and data frames) and using the You can write the transformed parameters block in one line with vector[N] scale = beta[1] + beta[2] * Density + sigma_D *r_Day[Day]; if you define Density in the data block. (e.g. Get the week's most popular data science and artificial intelligence research sent straight to your inbox every Saturday. ∙ asked Sep 15 '18 at 21:49. Package for Bayesian model averaging and variable selection for linear models, generalized linear models and survival models (cox regression). Ask Question Asked 3 years, 6 months ago. MathJax reference. A robust implementation of hyper-parameters and optional … Greater Ani (Crotophaga major) is a cuckoo species whose females occasionally lay eggs in conspecific nests, a form of parasitism recently explored []If there was something that always frustrated me was not fully understanding Bayesian inference. We demonstrate the functionality through worked examples. Throughout the Bayesian approach is implemented using R and appropriate illustrations are made. 06/04/2018 ∙ by Andreas Bender, et al. share, Accelerated failure time (AFT) models are used widely in medical researc... Keywords: Bayesian Inference, Right censoring, LaplaceApproximation, Survival function. In this site design / logo © 2020 Stack Exchange Inc; user contributions licensed under cc by-sa. Survival Analysis is a sub discipline of statistics. Why do most Christians eat pork when Deuteronomy says not to? Bayesian Time-to-Event Analysis We used Bayesian analysis to estimate pronghorn survival, mortality rates, and to conduct mortality risk regression from time-to-event data (Ibrahim et al. Description Usage Arguments Details Value Author(s) References See Also Examples. regression modelling by providing a user-friendly interface (users specify Amsterdam: Academic Press. Estimation of the Survival Distribution 1. the function spCopulaCoxph). Bayesian survival analysis with BUGS. My students worked on some excellent projects, and I invited them to write up their results as guest articles for this blog. 0 Briefly speaking, you just need to ignore the spred=s0 in the prediction settings, that is, prediction=list(xpred=xpred) is sufficient. How to do Bayesian inference with some sample data, and how to estimate parameters for your own data. With the release of Stata 14 came the mestreg command to fit multilevel ... estimation. ∙ Implementing that semiparametric model in PyMC3 involved some fairly complex numpy code and nonobvious probability theory equivalences. This post illustrates a parametric approach to Bayesian survival analysis in PyMC3. "Many books have been published concerning survival analysis or Bayesian methods; Bayesian Survival Analysis is the first comprehensive treatment that combines these two important areas of statistics. Join one of the world's largest A.I. This tutorial provides an introduction to survival analysis, and to conducting a survival analysis in R. This tutorial was originally presented at the Memorial Sloan Kettering Cancer Center R-Presenters series on August 30, 2018. Survivalanalysesareparticu-larly common in health and medical research, where a classic example of survival outcome dataisthetimefromdiagnosisofadiseaseuntiltheoccurrenceofdeath. In some fields it is called event-time analysis, reliability analysis or duration analysis. Usage. McElreath, Richard. ∙ rev 2020.12.2.38094, The best answers are voted up and rise to the top, Cross Validated works best with JavaScript enabled, Start here for a quick overview of the site, Detailed answers to any questions you might have, Discuss the workings and policies of this site, Learn more about Stack Overflow the company, Learn more about hiring developers or posting ads with us, Stuck with package example code in R - simulating data to fit a model, https://rdrr.io/cran/spBayesSurv/man/survregbayes.html, “Question closed” notifications experiment results and graduation, MAINTENANCE WARNING: Possible downtime early morning Dec 2, 4, and 9 UTC…, Survival analysis: continuous vs discrete time, Interval censored Cox proportional hazards model in R. In survival analysis, why do we use semi-parametric models (Cox proportional hazards) instead of fully parametric models? Is it possible to just construct a simple cable serial↔serial and send data from PC to C64? Cross Validated is a question and answer site for people interested in statistics, machine learning, data analysis, data mining, and data visualization. In spBayesSurv: Bayesian Modeling and Analysis of Spatially Correlated Survival Data. 0 Viewed 508 times 1. To be more clear, a new example is attached at the end. ∙ How can one prevent invaders to use their city walls against themselves? I am going through R's function indeptCoxph() in the spBayesSurv package which fits a bayesian Cox model. ∙ However recently Bayesian models are also used to estimate the survival rate due to their ability to handle design and analysis issues in clinical research.. References indirect effects with the additive hazards model. Various confidence intervals and confidence bands for the Kaplan-Meier estimator are implemented in thekm.ci package.plot.Surv of packageeha plots the … Asking for help, clarification, or responding to other answers. share, To better understand effects of exposure to food allergens, food challen... How to avoid overuse of words like "however" and "therefore" in academic writing? The rstanarm package facilitates Bayesian We Bayesian methods were previously used by many authors in survival analysis. I have previously written about Bayesian survival analysis using the semiparametric Cox proportional hazards model. None of these factors were found to be significant effect survival of lung cancer patients. Not only is the package itself rich in features, but the object created by the Surv() function, which contains failure time and censoring information, is the basic survival analysis data structure in R. Dr. Terry Therneau, the package author, began working on the survival package in 1986. 2 Bayesian Survival Analysis Using rstanarm analysis(engineering),andeventhistoryanalysis(sociology). r bayesian survival-analysis stan rstan. ∙ Doing Bayesian Data Analysis, Second Edition: A Tutorial with R, JAGS, and Stan. I am confused by some of the input parameters to this functions. Demonstrate an understanding of the theoretical basis of Survival Analysis and assumptions related to different Survival Analysis models 2. to decide the ISS should be a zero-g station when the massive negative health and quality of life impacts of zero-g were known? 2016. 11/26/2020 ∙ by Odd O. Aalen, et al. and includes generalised linear models (GLMs), generalised linear mixed models Bayesian Survival Analysis with Data Augmentation. The survival package is the cornerstone of the entire R survival analysis edifice. Posted on March 5, 2019 by R on in R bloggers | 0 Comments [This article was first published on R on , and kindly contributed to R-bloggers]. ∙ Pontificia Universidad Católica de Chile ∙ 0 ∙ share Survival analysis is one of the most important fields of statistics in medicine and the biological sciences. Viewed 2k times 1 $\begingroup$ I am going through R's function indeptCoxph() in the spBayesSurv package which fits a bayesian Cox model. (I also had some questions about the R code which I have posted separately on Stack Overflow: Stuck with package example code in R - simulating data to fit a model). analysis in applied research. Bayesian Survival Analysis Author: Austin Rochford. Lc_decg. Thanks for contributing an answer to Cross Validated! Is it considered offensive to address one's seniors by name in the US? Should it not only contain the predictor covariates? ∙ Over the last few years, there has been increased interest shown in the application of survival analysis based on Bayesian methodology. 0 2nd ed. (I also had some questions about the R code which I have posted separately on Stack … Package for Bayesian model averaging and variable selection for linear models, generalized linear models and survival models (cox regression). Best way to let people know you aren't dead, just taking pictures? Bayesian Survival Analysis Using the rstanarm R Package 02/22/2020 ∙ by Samuel L. Brilleman, et al. Survival analysis studies the distribution of the time to an event. We illustrate these concepts by analyzing a mastectomy data set from R ’s HSAUR package. Theprodlim package implements a fast algorithm and some features not included insurvival. 0 Interpreting the result of an Bayesian data analysis is usually straight forward. Here we will showcase some R examples of Bayesian survival analysis. Statistical Rethinking: A Bayesian Course with Examples in R … Request PDF | Bayesian survival analysis in clinical trials: What methods are used in practice? Its applications span many fields across medicine, biology, engineering, and social science. Bayesian survival analysis for "Game of Thrones" Last fall I taught an introduction to Bayesian statistics at Olin College. In this course you will learn how to use R to perform survival analysis. Description . This tutorial shows how to fit and analyze a Bayesian survival model in Python using PyMC3. share, Prognostic models in survival analysis are aimed at understanding the How to avoid boats on a mainly oceanic world? Its applications span many fields across medicine, biology, engineering, and social science. anticipate these implementations will increase the uptake of Bayesian survival Alternatively, the newly developed function survregbayes (https://rdrr.io/cran/spBayesSurv/man/survregbayes.html) is more user-friendly to use, which fits three popular semiparametric survival models (either non-, iid-, CAR-, or GRF-frailties): proportional hazards, accelerated failure time, and proportional odds. Given that my data is just a set of survival times between 0 and 100, along with censored (yes/no) information, how would I use this function and how should I handle the input "s"? ∙ only on the survival modelling functionality. Bayesian approaches were used for monitoring in 14 trials and for the final analysis only in 14 trials. article we describe how the rstanarm R package can be used to fit a wide range 177 1 1 silver badge 10 10 bronze badges. ∙ Interval Censored Failure Times, A flexible parametric accelerated failure time model, DeepHazard: neural network for time-varying risks, Time-dependent mediators in survival analysis: Modelling direct and Comparison of CPH, accelerated failure time model or neural networks for survival analysis, Survival Analysis on Rare Event Data predicts extremely high survival times, survival analysis using unbalanced sample, Simulation in R of data based on Cox proportional-hazards model for power analysis. By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy. share. This includes standard parametric How to dry out a soaked water heater (and restore a novice plumber's dignity)? ∙ Moore ( 2016 ) also provides a nice introduction to survival analysis with R . The suite of models that can be estimated using rstanarm is broad How do I respond as Black to 1. e4 e6 2.e5? Journal of the American Statistical Association "This is one … Why do Arabic names still have their meanings? The function example is conducted under the framework of spatial copula models (i.e. Survival analysis studies the distribution of the time to an event. Kaplan-Meier: Thesurvfit function from thesurvival package computes the Kaplan-Meier estimator for truncated and/or censored data.rms (replacement of the Design package) proposes a modified version of thesurvfit function. models, as well as standard parametric accelerated failure time (AFT) models. communities, © 2019 Deep AI, Inc. | San Francisco Bay Area | All rights reserved. Module Specification 2020-21 – 2463 Module Intended Learning Outcomes Upon successful completion of the module a student will be able to: 1. share. What is the role of the "prediction" input parameter? Considering T as the random variable that measures time to event, the survival function $$S(t)$$ can be defined as the probability that $$T$$ is higher than a given time $$t$$ , i.e., $$S(t) = P(T > t)$$ . Parametric models of survival are simpler to … What led NASA et al. ∙ It was then modified for a more extensive training at Memorial Sloan Kettering Cancer Center in March, 2019.


text:
# One-column figure in a two-column document : top and bottom alignment with text

I have a tall image in a figure float in a two-column document that I want alone in a single column. I would like the top of the image and the bottom of the figure caption to be both vertically aligned with the text area.

What I do presently is to adjust manually the spacing between the figure and the caption with \captionsetup{skip=1.5cm}.

Is there a way to have the skip of the figure caption to automatically eat all the remaining vertical space within the column instead of doing it manually?

Here is a MWE to illustrate my problem:

\documentclass[twocolumn]{article}

\usepackage{lipsum} % for the MWE
\usepackage{caption, graphicx}

\begin{document}
\begin{figure}[!p]
\captionsetup{skip=1.5cm}
\centering
\rule{\columnwidth}{0.9\textheight} % for the MWE
%\includegraphics[width=1\columnwidth]{my_image} % what I do
\caption{Some Caption}
\end{figure}
\lipsum % for the MWE
\end{document}

Which yields to:

Use a minipage with a height of \textheight, add a \vfill before caption.

\documentclass[twocolumn]{article}

\usepackage{lipsum} % for the MWE
\usepackage{caption,graphicx}

\begin{document}
\begin{figure}[!p]
%\smallskip   %%if needed
\begin{minipage}[t][\textheight]{\columnwidth}
\centering
\rule{\columnwidth}{0.9\textheight} % for the MWE
%\includegraphics[height=0.9\textheight, width=\coulmnwidth]{example-image}

\vfill    %% leave that blank line above
\caption{some caption}
\end{minipage}
\end{figure}
\lipsum % for the MWE
\end{document}


text:
# Write True or False. Give reasons for your answer:            A triangle ABC can be constructed in which $\angle B =60^{\circ}, \angle C=45^{\circ}$ and AB + BC + AC = 12 cm.

Given :$\angle B =60^{\circ}, \angle C=45^{\circ}$ ,  AB + BC + AC = 12 cm.

We know that the sum of interior angles of a triangle is $180^{\circ}$

$\angle B +\angle C=60^{\circ}+45^{\circ}=105^{\circ}$

$105^{\circ}<180^{\circ}$

Sum of two angles is less than $180^{\circ}$

Also, sum of all the sides is given as 12 cm, which does not contradict any property of a triangle.

Hence this type of triangle can be constructed.

Therefore the given statement is True.

### Preparation Products

##### Knockout JEE Main April 2021 (One Month)

Personalized AI Tutor and Adaptive Time Table, Self Study Material, Weekend Live Classes, Mentorship from our Experts, Unlimited Mock Tests and Personalized Analysis Reports, 24x7 Doubt Chat Support,.

₹ 14000/- ₹ 4999/-
##### Knockout NEET Aug 2021 (One Month)

Personalized AI Tutor and Adaptive Time Table, Self Study Material, Weekend Live Classes, Mentorship from our Experts, Unlimited Mock Tests and Personalized Analysis Reports, 24x7 Doubt Chat Support,.

₹ 14000/- ₹ 4999/-
##### Knockout JEE Main May 2021

Personalized AI Tutor and Adaptive Time Table, Self Study Material, Weekend Live Classes, Mentorship from our Experts, Unlimited Mock Tests and Personalized Analysis Reports, 24x7 Doubt Chat Support,.

₹ 22999/- ₹ 9999/-
##### Knockout NEET Aug 2021

Personalized AI Tutor and Adaptive Time Table, Self Study Material, Weekend Live Classes, Mentorship from our Experts, Unlimited Mock Tests and Personalized Analysis Reports, 24x7 Doubt Chat Support,.

₹ 22999/- ₹ 9999/-


text:
# The normal distribtuion?

• Jun 24th 2011, 11:58 AM
homeylova223
The normal distribtuion?
A set of data is normally distributed with a mean of 140 and a standard deviation of 20.

1. What percent of data is between 100 and 150?

2. Find the value that defines the 75th percentile.

I am having trouble figuring number one out because one is below the mean and the other one is above the mean? Is there a formula I can use a 150 is not part of stat deviation.
• Jun 24th 2011, 12:19 PM
FernandoRevilla
Re: The normal distribtuion?
Quote:

Originally Posted by homeylova223
I am having trouble figuring number one out because one is below the mean and the other one is above the mean? Is there a formula I can use a 150 is not part of stat deviation.

No problem, just routine. For example

$p(100\leq x\leq 150)=p\left(\dfrac{100-140}{20}\leq z\leq\dfrac{150-140}{20}\right)=\ldots$

Now use the table of the $N(0,1)$ distribution.
• Jun 24th 2011, 02:13 PM
homeylova223
Re: The normal distribtuion?
To find the percentile I found this formula online not in my text book

(75/100) (n+1) Will give me the percentile but what would I plug into n because this is normal distribution and not a set for example 99.7 percent of the data is three standard deviation from the mean. So what would I do?

Any help would be great.
• Jun 24th 2011, 05:16 PM
mr fantastic
Re: The normal distribtuion?
Quote:

Originally Posted by homeylova223
To find the percentile I found this formula online not in my text book

(75/100) (n+1) Will give me the percentile but what would I plug into n because this is normal distribution and not a set for example 99.7 percent of the data is three standard deviation from the mean. So what would I do?

Any help would be great.

You need to go to your class notes and or textbook and review the many examples that are sure to be there. You also need to arrange for one-on-one help from your instructor or a tutor because you have serious problems with this topic.

The formula you have found is not relevant to your question. It applies to discrete data.

The 75th percentile is given by the value of a such that Pr(X < a) = 0.75.

So find the value z* such that Pr(Z < z*) = 0.75.

Then use the fact that it follows from Z = (X - mean)/(standard deviation) that z* = (a - 140)/20. Solve for a.

If none of this makes sense, you need to re-read my first two lines. It is certain that youir textbook has examples that explain all this.