Adhikari - 1 year ago 87

C# Question

`I have following array {9, 0, 2, -5, 7} and from this array i need to find the the square pairs <2, 7> and <7, 9> where first element must be less than second.

And <-5, 9> and <0, 9> are not square pairs, even though they sum to perfect squares,

because both members of a square pair have to be greater than 0.

`bool ans;`

int[] number = new int[]{9,0,2,-5,7};

for (int j = 0; j < number.Length; j++)

{

if (number[j]<number[j+1])

ans = IsPerfectSquares(number[j]+number[j+1]);

if(ans)

count++;

}

}

public static bool IsPerfectSquares(int input)

{ long SquareRoot = (long)Math.Sqrt(input);

return ((SquareRoot * SquareRoot) == input);

} `

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

C# Linq:

```
int[] array = {9, 0, 2, -5, 7};
int len = array.Length;
var pairs =
from i in Enumerable.Range(0, len-1)
where array[i] > 0
from j in Enumerable.Range(i+1, len-i-1)
where array[j] > 0
let sqrt = (int)Math.Sqrt(array[i] + array[j])
where array[i] + array[j] == sqrt * sqrt
select new {
A = Math.Min(array[i], array[j]),
B = Math.Max(array[i], array[j])
};
//or: select new int[] { ... };
```

Results:

```
{ A = 7, B = 9 }
{ A = 2, B = 7 }
```

Java: (also works in C# with slightly different syntax)

```
int[] array = { 9, 0, 2, -5, 7 };
List<int[]> pairs = new ArrayList<int[]>();
for (int i = 0; i < array.length - 1; ++i) {
if (array[i] <= 0) continue;
for (int j = i + 1; j < array.length; ++j) {
if (array[j] <= 0) continue;
int sqrt = (int)Math.sqrt(array[i] + array[j]);
if (array[i] + array[j] == sqrt * sqrt)
pairs.add(new int[] { array[i], array[j] });
}
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**