Skip to content

[Hacker Rank]: Project Euler #3: Largest prime factor. Solved ✓ #230

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package ae.hackerrank.projecteuler;

/**
* Even Fibonacci numbers.
*
* @link Problem definition [[docs/hackerrank/projecteuler/euler003.md]]
*/
public class Euler003 {

private Euler003() {}

private static Long primeFactor(Long n) {
if (n < 2) {
return null;
}

Long divisor = n;
Long maxPrimeFactor = null;

int i = 2;
while (i <= Math.sqrt(divisor)) {
if (divisor % i == 0) {
divisor = divisor / i;
maxPrimeFactor = divisor;
} else {
i += 1;
}
}

if (maxPrimeFactor == null) {
return n;
}

return maxPrimeFactor;
}

/**
* Even Fibonacci numbers.
*/
public static Long euler003(long n) {
return primeFactor(n);
}
}

//CHECKSTYLE.ON: JavadocParagraph
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package ae.hackerrank.projecteuler;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.io.IOException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import util.JsonLoader;


@TestInstance(Lifecycle.PER_CLASS)
class Euler003Test {

public static class Euler003TestCase {
public Long n;
public Long expected;
}

private List<Euler003TestCase> testCases;

@BeforeAll
public void setup() throws IOException {
String path = String.join("/",
"hackerrank",
"projecteuler",
"euler003.testcases.json");

this.testCases = JsonLoader.loadJson(path, Euler003TestCase.class);
}

@Test void euler003() {

for (Euler003TestCase test : testCases) {
Long solutionFound = Euler003.euler003(test.n);

assertEquals(test.expected, solutionFound,
"%s(%d) => must be: %s".formatted(
"Euler003.euler003",
test.n,
test.expected
)
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[
{ "n": 10, "expected": 5 },
{ "n": 17, "expected": 17 }
]