We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Project Euler #30: Digit Nth powers
Project Euler #30: Digit Nth powers
+ 0 comments code in c
int main() {
int n; scanf("%d",&n); unsigned long long int sum=0; for (long i =2; i<1000000; i++) { long temp = i; unsigned long long int sum1 = 0; while (temp>0) { int a = temp%10; sum1 +=(unsigned long long int) pow(a, n); temp = temp/10; } if (sum1 == i) { sum += sum1; } } printf("%lld",sum); return 0;
}
+ 0 comments C++
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> arr(10); for (int i=0; i<=9; i++) { int p = pow(i, n); arr[i] = p; } int S = 0; for (int i=100; i<1000000; i++) { int num = i, sum=0; while(num>0) { int z = num%10; sum = sum+arr[z]; num = num/10; } if (sum==i) S = S + sum; } cout << S; return 0; }
+ 1 comment My sense was to do the following.
MIN = 2 MAX = 1000000 def compute(value): ans = sum(i for i in range(MIN, MAX) if i == power_digit_sum(value, i)) return str(ans) def power_digit_sum(value, n): return sum(int(c) ** value for c in str(n)) if __name__ == "__main__": value = int(input()) print(compute(value))
+ 1 comment My Approach - First find all possible numbers that a K-digit number could have for example I treated [1,2,3],[2,1,3],[1,3,2],[2,3,1],[3,1,2],[3,2,1] all as same and I find only one of them and not repeated numbers with same digits (using recursive appraoch) since what we are interested in only digits which constitute K-digit number . this way my algorithm is very fast and will also work if N (input) is even more than 6 .
+ 0 comments You can still use brute-force. Just do some experiments to determine lower and upper limit for i, then you will pass all cases.
def Digit_Nth_Powers(n,lower,upper): sumList = 0 for i in range(lower,upper): digits = list(map(int,str(i))) tempSum = 0 for j in digits: tempSum += j**n if i == tempSum: sumList += i return sumList if __name__ == '__main__': n = int(input()) # Lower and upper limit is determined by experiments for faster code execution if n == 3: lower,upper = [1*(10**2), 1*(10**3)] elif n == 4: lower,upper = [1*(10**3), 1*(10**4)] elif n == 5: lower,upper = [2*(10**3), 2*(10**5)] elif n == 6: lower,upper = [1*(10**5), 6*(10**5)] sumList = Digit_Nth_Powers(n,lower,upper) print(sumList)
Load more conversations
Sort 43 Discussions, By:
Please Login in order to post a comment