I was asked by a friend :
If 2^10 = 1024
, we can take 1024 and break and summarize its digits :
1+0+2+4 = 7.
This is easy.
However When the input is 2^30000
( the input actually is a long string "1000..."
) --there is no .net type which can hold this value .
So there must be a trick to sum its digits (digits of the decimal value)....
Edited :
Related trick ( for finding 10^20 - 16
)
100 = 10^2 (one and two zeros)
10^20 = (one and 20 zeros)
hence:
10^20 - 16 = 18 nines, an eight and four.
18*9+8+4 = 174
But I haven't succeeded converting this solution to my problem.( I tried quite a lot).
*Im tagging this question as .net because I can use string functions , math functions from .net library.*
Question
Is there any trick here which can allow me to sum many many numbers which is the result of x^n
?
What is the trick here ?
Edited #2 : Added the .net2 tag (where biginteger is unavailable) - I'm wondering how I could do it without biginteger.(i'm looking for the hidden trick)
From http://blog.singhanuvrat.com/problems/sum-of-digits-in-ab:
public class Problem_16 {
public long sumOfDigits(int base, int exp) {
int numberOfDigits = (int) Math.ceil(exp * Math.log10(base));
int[] digits = new int[numberOfDigits];
digits[0] = base;
int currentExp = 1;
while (currentExp < exp) {
currentExp++;
int carry = 0;
for (int i = 0; i < digits.length; i++) {
int num = base * digits[i] + carry;
digits[i] = num % 10;
carry = num / 10;
}
}
long sum = 0;
for (int digit : digits)
sum += digit;
return sum;
}
public static void main(String[] args) {
int base = 2;
int exp = 3000;
System.out.println(new Problem_16().sumOfDigits(base, exp));
}
}
c#
public class Problem_16 {
public long sumOfDigits(int base1, int exp) {
int numberOfDigits = (int) Math.Ceiling(exp * Math.Log10(base1));
int[] digits = new int[numberOfDigits];
digits[0] = base1;
int currentExp = 1;
while (currentExp < exp) {
currentExp++;
int carry = 0;
for (int i = 0; i < digits.Length; i++) {
int num = base1 * digits[i] + carry;
digits[i] = num % 10;
carry = num / 10;
}
}
long sum = 0;
foreach (int digit in digits)
sum += digit;
return sum;
}
}
void Main()
{
int base1 = 2;
int exp = 3000000;
Console.WriteLine (new Problem_16().sumOfDigits(base1, exp));
}