mirror of
https://github.com/TheAlgorithms/Java.git
synced 2026-03-13 08:40:43 +08:00
* Update SinglyLinkedList
* Refactor MergeSortedSinglyLinkedList to single file * Create Problem09 and Problem10 in Project Euler
This commit is contained in:
30
ProjectEuler/Problem09.java
Normal file
30
ProjectEuler/Problem09.java
Normal file
@@ -0,0 +1,30 @@
|
||||
package ProjectEuler;
|
||||
|
||||
/**
|
||||
* A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
|
||||
* <p>
|
||||
* a^2 + b^2 = c^2
|
||||
* For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
|
||||
* <p>
|
||||
* There exists exactly one Pythagorean triplet for which a + b + c = 1000.
|
||||
* Find the product abc.
|
||||
* <p>
|
||||
* link: https://projecteuler.net/problem=9
|
||||
*/
|
||||
public class Problem09 {
|
||||
public static void main(String[] args) {
|
||||
assert solution1() == 31875000;
|
||||
}
|
||||
|
||||
private static int solution1() {
|
||||
for (int i = 0; i <= 300; ++i) {
|
||||
for (int j = 0; j <= 400; ++j) {
|
||||
int k = 1000 - i - j;
|
||||
if (i * i + j * j == k * k) {
|
||||
return i * j * k;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1; /* should not happen */
|
||||
}
|
||||
}
|
||||
55
ProjectEuler/Problem10.java
Normal file
55
ProjectEuler/Problem10.java
Normal file
@@ -0,0 +1,55 @@
|
||||
package ProjectEuler;
|
||||
|
||||
/**
|
||||
* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
|
||||
* <p>
|
||||
* Find the sum of all the primes below two million.
|
||||
* <p>
|
||||
* link: https://projecteuler.net/problem=10
|
||||
*/
|
||||
public class Problem10 {
|
||||
public static void main(String[] args) {
|
||||
long[][] testNumbers = {
|
||||
{2000000, 142913828922L},
|
||||
{10000, 5736396},
|
||||
{5000, 1548136},
|
||||
{1000, 76127},
|
||||
{10, 17},
|
||||
{7, 10}
|
||||
};
|
||||
|
||||
for (long[] testNumber : testNumbers) {
|
||||
assert solution1(testNumber[0]) == testNumber[1];
|
||||
}
|
||||
}
|
||||
|
||||
/***
|
||||
* Checks if a number is prime or not
|
||||
* @param n the number
|
||||
* @return {@code true} if {@code n} is prime
|
||||
*/
|
||||
private static boolean isPrime(int n) {
|
||||
if (n == 2) {
|
||||
return true;
|
||||
}
|
||||
if (n < 2 || n % 2 == 0) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) {
|
||||
if (n % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static long solution1(long n) {
|
||||
long sum = 0;
|
||||
for (int i = 2; i < n; ++i) {
|
||||
if (isPrime(i)) {
|
||||
sum += i;
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user