Waste less time on Facebook — follow Brilliant.
×

Fastest method to sum up the left diagonal elements of a square array

I've been observing people using the following method for summing up the left diagonal elements of a square array \(a\) of dimensions \(n\) by \(n\):

1
2
3
4
5
//s is an integer datatype which has been initialised to 0 beforehand
for(int i = 0; i < n; i++)
    for(int j = 0; j < n; j++)
        if(i == j)
            s += a[i][j];

Wouldn't the following account for a faster method?

1
2
for(int i = 0; i < n; i++)
    s += a[i][i];

Note by Arkajyoti Banerjee
1 week, 4 days ago

No vote yet
1 vote

Comments

There are no comments in this discussion.

×

Problem Loading...

Note Loading...

Set Loading...