Sum of all numbers that can be formed with permutations of n digits - GeeksforGeeks
Given n distinct digits (from 0 to 9), find sum of all n digit numbers that can be formed using these digits. It is assumed that numbers formed with leading 0 are allowed.
Read full article from Sum of all numbers that can be formed with permutations of n digits - GeeksforGeeks
Given n distinct digits (from 0 to 9), find sum of all n digit numbers that can be formed using these digits. It is assumed that numbers formed with leading 0 are allowed.
Total numbers that can be formed using n digits is total number of permutations of n digits, i.e factorial(n). Now, since the number formed is a n-digit number, each digit will appear factorial(n)/n times at each position from least significant digit to most significant digit. Therefore, sum of digits at a position = (sum of all the digits) * (factorial(n)/n).
Considering the example digits as 1 2 3 factorial(3)/3 = 2 Sum of digits at least significant digit = (1 + 2 + 3) * 2 = 12 Similarly sum of digits at tens, hundreds place is 12. (This sum will contribute as 12 * 100) Similarly sum of digits at tens, thousands place is 12. (This sum will contribute as 12 * 1000) Required sum of all numbers = 12 + (10 * 12) + (100 * 12) = 1332
int getSum(int arr[],int n){ // calculate factorial int fact = factorial(n); // sum of all the given digits at different // positions is same and is going to be stored // in digitsum. int digitsum = 0; for (int i=0; i<n; i++) digitsum += arr[i]; digitsum *= (fact/n); // Compute result (sum of all the numbers) int res = 0; for (int i=1, k=1; i<=n; i++) { res += (k*digitsum); k = k*10; } return res;}