A common technique in parallelization is to fuse nested for loops like this
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
to
for(int x=0; x<n*n; x++) {
int i = x/n; int j = x%n;
I'm wondering how I can do this to fuse a triangle loop like this
for(int i=0; i<n; i++) {
for(int j=0; j<i+1; j++) {
This has n*(n+1)/2
iterations. Let's call the fused iteration x
. Using the quadratic formula I have come up with this:
for(int x=0; x<(n*(n+1)/2); x++) {
int i = (-1 + sqrt(1.0+8.0*x))/2;
int j = x - i*(i+1)/2;
Unlike fusing the square loop this requires using the sqrt
function and conversions from int to float and from float to int.
I'm wondering if there is a simpler or more efficient way of doing this? For example a solution which does not require the sqrt
function or conversions from int to float or float to int.
Edit: I don't want a solution which depends on previous or next iterations. I only want solutions like int i = funci(x) and int j = funcj(x,i)
Here is some code showing that this works:
#include <stdio.h>
#include <math.h>
int main() {
int n = 5;
int cnt = 0;
for(int i=0; i<n; i++) {
for(int j=0; j<i+1; j++) {
printf("%d: %d %d
", cnt++, i,j);
}
} printf("
");
int nmax = n*(n+1)/2;
for(int x=0; x<nmax; x++) {
int i = (-1 + sqrt(1.0+8.0*x))/2;
int j = x - i*(i+1)/2;
printf("%d: %d %d
", x,i,j);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…