Skip to content
Open
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
37 changes: 29 additions & 8 deletions app/src/main/java/algorithms/Primes.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@ public static boolean IsPrime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i * i <= n; i++) { // Optimized loop condition
if (n == 2) {
return true;
}
if (n % 2 == 0) {
return false;
}
for (int i = 3; i * i <= n; i += 2) { // Only check odd numbers
if (n % i == 0) {
return false;
}
Expand All @@ -28,9 +34,13 @@ public static boolean IsPrime(int n) {
*/
public static int SumPrimes(int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
if (n < 2) {
return 0;
}
sum += 2; // Include 2 as the first prime
for (int i = 3; i < n; i += 2) { // Only check odd numbers
if (IsPrime(i)) {
sum = sum + i;
sum += i;
}
}
return sum;
Expand All @@ -44,16 +54,27 @@ public static int SumPrimes(int n) {
*/
public static Vector<Integer> PrimeFactors(int n) {
Vector<Integer> ret = new Vector<Integer>();

// Handle 2 separately
while (n % 2 == 0) {
ret.add(2);
n /= 2;
}

for (int i = 2; i * i <= n; i++) { // Optimized loop condition
while (n % i == 0 && IsPrime(i)) { // Optimized to handle repeated factors
ret.add(i);
n /= i; // Reduce n to avoid redundant checks.
// Check odd numbers only
for (int i = 3; i * i <= n; i += 2) {
while (n % i == 0) {
if (IsPrime(i)) {
ret.add(i);
n /= i;
} else {
break;
}
}
}
if (n > 1) { // Add any remaining prime factor.
ret.add(n);
}
return ret;
}
}
}