Project Euler #30: Digit Nth powers

Sort by

recency

|

53 Discussions

|

  • + 0 comments

    import java.io.; import java.util.;

    public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(); // Read the input
    
        long sum = 0; // Variable to store the sum
    
        for (int i = 10; i <= 999999; i++) { 
            if (isDigitPowerSum(i, n)) { 
                sum += i; 
            }
        }
    
        System.out.println(sum);
    }
    public static boolean isDigitPowerSum(int num, int n) {
    
        int sum = 0 ;
        int orignal= num;
        while(num>0){
            int digit = num % 10;
            sum += Math.pow(digit, n);
            num /= 10;
        }
        return sum==orignal;
    
    }
    

    }

  • + 0 comments

    //C# using System;

    class Program { static int PowerSum(int num, int power) { int sum = 0; int temp = num;

        while (temp > 0)
        {
            int digit = temp % 10;
            sum += (int)Math.Pow(digit, power);
            temp /= 10;
        }
    
        return sum;
    }
    
    static void Main()
    {
        int N = int.Parse(Console.ReadLine());
        int totalSum = 0;
    
        for (int i = 10; i <= 999999; i++)
        {
            if (i == PowerSum(i, N))
            {
                totalSum += i;
            }
        }
    
        Console.WriteLine(totalSum);
    }
    

    }

  • + 0 comments
    #python
    pw=int(input())
    res=set()
    for num0 in range(100, 1000000):
        su=0
        num=num0
        while num!=0:
            su+=(num %10)**pw
            num//=10
        if su==num0:
            res.add(num0)
    print(sum(res))
    
  • + 0 comments

    This code workes well using python 3

    def main():
        n = int(input())
        total_sum = 0
    
        for i in range(2, 10**6):
            temp = i
            sum1 = 0
    
            while temp > 0:
                a = temp % 10
                sum1 += a**n
                temp = temp // 10
    
            if sum1 == i:
                total_sum += sum1
    
        print(total_sum)
    
    if __name__ == "__main__":
        main()
    
  • + 0 comments

    for n=5, it also has numbers ranging from 1000 to 1000000, so the solution in python will be

    n=int(input().strip()) sum_=0 if n==5: sum_ = sum([i for i in range(10**(n-2), 10**(n+1)) if sum(int(digit)n for digit in str(i)) == i]) print(sum_) else: sum_ = sum([i for i in range(10(n-1), 10**(n)) if sum(int(digit)**n for digit in str(i)) == i]) print(sum_)