Search code examples
vb.netdigitssum-of-digits

How To Split An Integer


I am trying to create an additive persistence program where the user inputs a number and the program outputs the total number of iterations (or additive persistence).

I want to code it so that I do not use the string data type.
Are there any built-in functions or otherwise that I can use so that I can split a large number into its separate digits?

Things to note:

  1. I am coding in a console application in VB.Net
  2. I am relatively new at coding

Solution

  • To get the last digit of a number in base 10, you can use the modulo operator, known as Mod, thus:

    1234 Mod 10 = 4
    32 Mod 10 = 2
    

    and so on.

    When you have the last digit, it can in essence be chopped off by using integer division:

    1234 \ 10 = 123
    32 \ 10 = 3
    

    So now the process can be repeated to get what has become the last digit. Once the original number has been reduced to 0, the algorithm has finished.

    As you don't need the digits in any particular order, we don't have to worry about that.

    So, given:

    Function GetDigits(n As Int64) As List(Of Int64)
        Dim digits As New List(Of Int64)
        While n > 0
            digits.Add(n Mod 10)
            n = n \ 10
        End While
    
        Return digits
    
    End Function
    

    You could do:

    Console.WriteLine(String.Join(" ", GetDigits(12345678900)))
    

    to get an output of:

    0 0 9 8 7 6 5 4 3 2 1

    I used an Int64 (a.k.a. Long) for the parameter of GetDigits so that you can use numbers with more digits than an Int32 (a.k.a. Integer) can hold.

    From that, you can:

    Function AdditivePersistence(n As Int64) As Integer
        Dim pers = 0
        While n > 9
            pers += 1
            n = GetDigits(n).Sum()
        End While
    
        Return pers
    
    End Function