From b71c06afeff396b24d7142ddb8fc2b6e2993f651 Mon Sep 17 00:00:00 2001 From: Vitali Plagov Date: Wed, 24 Jan 2024 10:13:08 +0200 Subject: [PATCH] Problem 30 --- .../problems/problems026to050/Problem030.java | 35 +++++++++++++++++++ .../problems026to050/Problem030Test.java | 13 +++++++ 2 files changed, 48 insertions(+) create mode 100644 src/main/java/net/projecteuler/problems/problems026to050/Problem030.java create mode 100644 src/test/java/net/projecteuler/problems/problems026to050/Problem030Test.java diff --git a/src/main/java/net/projecteuler/problems/problems026to050/Problem030.java b/src/main/java/net/projecteuler/problems/problems026to050/Problem030.java new file mode 100644 index 0000000..e10bff5 --- /dev/null +++ b/src/main/java/net/projecteuler/problems/problems026to050/Problem030.java @@ -0,0 +1,35 @@ +package net.projecteuler.problems.problems026to050; + +import java.util.stream.IntStream; + +public class Problem030 { + + private static final int POWER = 5; + + private static int sumOfFifthPowers(int number) { + return Integer.toString(number).chars() + .map(Character::getNumericValue) + .map(i -> (int) Math.pow(i, 5)) + .sum(); + } + + private static int getBound(int power, int base) { + var number = power * (int) Math.pow(base, 5); + var maxLength = Integer.toString(number).length(); + + while (Integer.toString(number).length() <= maxLength) { + power++; + number = power * (int) Math.pow(base, 5); + } + return number; + } + + public int solve() { + var start = getBound(POWER, 1); + var end = getBound(POWER, 9); + + return IntStream.rangeClosed(start, end) + .filter(number -> number == sumOfFifthPowers(number)) + .sum(); + } +} diff --git a/src/test/java/net/projecteuler/problems/problems026to050/Problem030Test.java b/src/test/java/net/projecteuler/problems/problems026to050/Problem030Test.java new file mode 100644 index 0000000..d0b7100 --- /dev/null +++ b/src/test/java/net/projecteuler/problems/problems026to050/Problem030Test.java @@ -0,0 +1,13 @@ +package net.projecteuler.problems.problems026to050; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class Problem030Test { + + @Test + void solve() { + assertEquals(443839, new Problem030().solve()); + } +}