简体   繁体   中英

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.

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!

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;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM