Skip to main content

Digital Sum

Digital Sum Digital Sum : The digital sum is the sum of the digits of a number taken iteratively till the result is less than 10. The problem statement is to get the number of integers less than 1 million where the digital sum is 1 and then, take the digital sum of this number which gives us the result. Note : Enable Javascript

Here is the recursive function in C#.

private void GetDigitalSum(double num, ref double num2) { //digital sum

double sum = 0;

for (int r = 0; r <= num.ToString().Length - 1; r++)
{
sum += double.Parse(num.ToString().Substring(r, 1));
}

if (sum.Equals(1))
{
num2 = -8;
return;
}
else
{
if (sum > 9)
{
GetDigitalSum(sum, ref num2);
}
else
{
num2 = sum;
}
}

}

//Here is calling subroutine

double no = 1;
double no2 = 0;
double sumr = 0;
double sumc = 0;

ArrayList ar = new ArrayList();

while (no < 1000000)
{
Application.DoEvents();
lblCounter.Text = no.ToString();

GetDigitalSum(no, ref no2);

if (no2.Equals(-8))
{
ar.Add(no);
sumr += double.Parse(no.ToString());
}

no += 1;

}

GetDigitalSum(ar.Count, ref no2);

MessageBox.Show(no2.ToString);

Click link to reveal answer

Comments