ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Sum of Digits

Visual Basic .NET

Goal -- WPM

Ready
Exercise Algorithm Area
1Public Module DigitSumCalculator
2
3' Calculates the sum of the digits of a non-negative integer.
4' For example, the sum of digits of 123 is 1 + 2 + 3 = 6.
5Public Function SumOfDigits(ByVal n As UInteger) As UInteger
6Dim sum As UInteger = 0
7
8' Handle the edge case where the input is 0.
9If n = 0 Then
10Return 0
11End If
12
13' Loop while the number is greater than 0.
14While n > 0
15' Get the last digit using the modulo operator.
16Dim digit As UInteger = n Mod 10
17' Add the digit to the sum.
18sum = sum + digit
19' Remove the last digit by integer division.
20n = n \\ 10
21End While
22
23Return sum
24End Function
25
26End Module
Algorithm description viewbox

Sum of Digits

Algorithm description:

This function computes the sum of the digits of a given non-negative integer. It iteratively extracts the last digit of the number using the modulo operator and adds it to a running sum. The number is then divided by 10 (integer division) to remove the last digit. This process continues until the number becomes zero. This is a fundamental operation used in various number theory problems, checksum calculations, and digital root computations.

Algorithm explanation:

The `SumOfDigits` function has a time complexity of O(log10 n), where n is the input number, because the number of iterations is proportional to the number of digits in n. The space complexity is O(1) as it only uses a constant amount of extra space for variables. The edge case of an input of 0 is handled correctly, returning 0. The loop invariant is that `sum` always holds the sum of digits of the original number that have already been processed, and `n` holds the remaining part of the number. The loop terminates when `n` becomes 0, at which point `sum` contains the total sum of all digits.

Pseudocode:

function sumOfDigits(n):
  sum = 0
  if n == 0:
    return 0
  while n > 0:
    digit = n modulo 10
    sum = sum + digit
    n = n integer divide 10
  return sum