I'm new to programming and Stack-overflow but I'm trying to create a list of prime factors from a number but it is returning more than one list and I don't know why. For example when I enter 10, it returns [2,5] and [2,5,5] instead of just [2,5]. Can someone explain what I'm doing wrong?
public class Solution {
ArrayList<Integer> primelist = new ArrayList<>();
ArrayList<Integer> findPrime(int num) {
for (int i = 2; i <= num; i++) {
if (num % i == 0) {
primelist.add(i);
num = num / i;
if (num == 1) { break;}
findPrime(num);
}
}
System.out.println(primelist);
return primelist;
}
public static void main(String[] args) {
Solution sol = new Solution();
sol.findPrime(30);//[2, 3, 5],[2, 3, 5, 5], [2, 3, 5, 5, 3, 5],[2, 3, 5, 5, 3, 5, 5]
sol.findPrime(10);//[2, 5],[2, 5, 5]
}
}
Im guessing you try to achieve the Sieve of Eratosthenes .
this works:
@Test
public void numbers() {
class Solution {
List<Integer> sieveOfEratosthenes(int n) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p) {
prime[i] = false;
}
}
}
List<Integer> primeNumbers = new LinkedList<>();
for (int i = 2; i <= n; i++) {
if (prime[i]) {
primeNumbers.add(i);
}
}
return primeNumbers;
}
}
//test it..
Solution sol = new Solution();
System.out.println(sol.sieveOfEratosthenes(10));
System.out.println(sol.sieveOfEratosthenes(100));
}
... which yields correct results:
[2, 3, 5, 7]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
i borrowed this code from this article , an detailed explanation of the steps of the algorithm can be found there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.