-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathPrimes.java
More file actions
59 lines (55 loc) · 1.38 KB
/
Primes.java
File metadata and controls
59 lines (55 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package algorithms;
import java.util.ArrayList;
public class Primes {
/**
* Checks if a number is prime
* test comment
* @param n The number to check.
* @return True if the number is prime, false otherwise.
*/
public static boolean IsPrime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i * i <= n; i++) { // Optimized loop condition
if (n % i == 0) {
return false;
}
}
return true;
}
/**
* Sums all prime numbers from 0 to n
*
* @param n The number of prime numbers to sum.
* @return The sum of the first n prime numbers.
*/
public static int SumPrimes(int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
if (IsPrime(i)) {
sum = sum + i;
}
}
return sum;
}
/**
* Finds all primes factors of a number
*
* @param n The number to find the prime factors of.
* @return An array list of all prime factors of n.
*/
public static ArrayList<Integer> PrimeFactors(int n) {
ArrayList<Integer> ret = new ArrayList<Integer>();
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.
}
}
if (n > 1) { // Add any remaining prime factor.
ret.add(n);
}
return ret;
}
}