nmagerko
nmagerko

Reputation: 6794

Add Elements Returned from a List

I have an algorithm that uses a List in Java that is declared like this:

public static List<Integer> primeFactors(int numbers) {
    int n = numbers; 
    List<Integer> factors = new ArrayList<Integer>();
    for (int i = 2; i <= n / i; i++) {
        while (n % i == 0) {
            factors.add(i);
            n /= i;
        }
    }
    if (n > 1) {
        factors.add(n);
    }
    return factors;
}

What I would like to be able to do is to take the primes returned by this function and add them. I know I can use

for (Integer integer : primeFactors(NUMBER))

to do something with every prime added to the List, so I am guessing the answer will be something along these lines when I add them. Is something like this possible?

Thanks for any and all help.

Upvotes: 0

Views: 85

Answers (2)

GiantRobot
GiantRobot

Reputation: 432

You can do addition of the elements that you want in your algorithm because you already iterating on the elements. the function will return 18 for primeFactors(65) -> 5*13

    public static void main(String[] args) {
    int sumOfPrimeFactors = primeFactors(65);
    System.out.println(sumOfPrimeFactors);
}

public static int primeFactors(int numbers) {
    int sum = 0;
    int n = numbers;
    int i;

    for (i = 2; i <= n / i; i++) {
        while (n % i == 0) {
            sum += i;

            n /= i;
        }
    }
    if (n > 1) {
        sum += n;
    }
    return sum;
}

Upvotes: 1

ElectronAnt
ElectronAnt

Reputation: 2195

So basically have a variable outside the loop, and then you can do something like this:

List list = primeFactors(NUMBER);
int sum = 0;
for(Integer number : list){
    sum += number;
}

At the end of that loop, sum will contain the number you want!

Upvotes: 2

Related Questions