Reputation: 109
I am trying to find prime factors of a range starting from min number to max number. SO lets say I have min value: 7 and max value: 10. I will need to find prime factors starting from 7 to 10. I am able to find prime factors of single number like 10 or 12 but I cant seem to do it for range within numbers 7 - 10. Here is what I wrote:
public static void primeFactors(int min, int max){
for(int i = 2; i <= max; i++){
while(min <= max && i % 2 == 0){
min = min / 2;
}
System.out.println("Factor: " + i);
}
}
}
Upvotes: 0
Views: 177
Reputation: 10695
If you wish to do this in a single loop, you need to keep track of all numbers of the input, e.g. by using an array:
public static void main(String[] args) {
// range [7, 10]
int[] inputs = IntStream.range(7, 11).toArray();
System.out.println(factorize(inputs));
}
private static Set<Integer> factorize(final int[] input) {
// no prime factors bigger than half the largest number
final int limit = input[input.length - 1] / 2;
final Set<Integer> factors = new HashSet<>();
for (int f = 2; f <= limit; f++) {
// even numbers are not primes
if (((f % 2) == 0) && (f > 2)) continue;
for (int i = 0; i < input.length; i++) {
while (input[i] % f == 0) {
input[i] /= f;
factors.add(f);
}
}
}
return factors;
}
Output:
[2, 3, 5]
However, if you have a method that computes prime factors of a number, calling that method could be simpler:
IntStream.range(7, 11).forEach(i -> factorizeSingleNumber(i));
Upvotes: 0