# java实现Write a method named isMadhavArray that returns 1

## 1. 美国面试试题2

A Madhav array has
the following property.
a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = …
The length of a Madhav array must be n*(n+1)/2 for some n.
Write a method named isMadhavArray that returns 1 if its array argument is a Madhav array,
otherwise it returns 0. If you are programming in Java or C# the function signature is int isMadhavArray(int[ ] a)
If you are programming in C or C++, the function signature is
int isMadhavArray(int a[ ], int len) where len is the number of elements in a.

## 2 代码实现：

```public class MadHavArray {
public static void main(String[] args) {

//         int a[] = {2,1,1};
//        int a[] = {2, 1, 1, 4, -1, -1};
//        int a[] = {6, 2, 4, 2, 2, 2, 1, 5, 0, 0};
//        int a[] = {18, 9, 10, 6, 6, 6};
int a[] = {-6, -3, -3, 8, -5, -4};//?
//        int a[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, -2, - 1};
//        int a[] = {3, 1, 2, 3, 0};
//        System.out.println(3/2);

}

public static int  isMadhavArray(int[]a){

int length = a.length;

int tmp=0;
for (int i=0;i<length/2;i++){ // 判断长度是否满足条件 n*(n+1)/2
int x = i*(i+1)/2;
if (x ==length){
tmp =1;
}
}
if (tmp==0){
return 0;
}

for (int i=1;i<=length/2;++i){
int sum =0;
for (int j = i*(i+1)/2 ; j< i+1;j++){ // a[2]+a[3] 和的实现
sum = sum + a[j]+a[j+1];

}
if (sum != a[0]){
return 0;
}else {
return 1;
}
}
return 0;
}
}```