Question

This code is copied from another user question and I`m curious how accumulate works here. I get the correct result from this code, but would like to know what parameters lcm takes when in "accumulate". The init as A and the sum of the range as b? Please help

#include <numeric>

int gcd(int a, int b)
{
    for (;;)
    {
        if (a == 0) return b;
        b %= a;
        if (b == 0) return a;
        a %= b;
    }
}

int lcm(int a, int b)
{
    int temp = gcd(a, b);

    return temp ? (a / temp * b) : 0;
}

int main()
{
    int arr[] = { 5, 7, 9, 12 };

    int result = std::accumulate(arr, arr + 4, 1, lcm);

    std::cout << result << '\n';
}
Was it helpful?

Solution

The first argument that lcm will take is the accumulated value so far (which starts at 1, the third argument of std::accumulate), and the second argument will be an element in arr. Next, whatever lcm returns is passed as the first argument and the next element in arr as the second.

See a reference for more details.

You could easily write a and b to the standard output inside lcm to see what's happening.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top