Write a C method named isPrepareSArray that returns 1 if its array argument is a PrepareS array, otherwise return 0.
A PrepareS 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] = ....
Then length of PrepareS array must be n*(n+1)/2 for some n.
Write a C method named isPrepareSArray that returns 1 if its array argument is a PrepareS array, otherwise return 0.
#include <stdio.h>
int main(int argc, const char * argv[])
int checkSize(int n)
Some Tracings:
a[0] = a[1] + a[2] = a[3]+a[4]+a[5] = a[6] + a[7] + a[8]+ a[9] = ....
Then length of PrepareS array must be n*(n+1)/2 for some n.
Write a C method named isPrepareSArray that returns 1 if its array argument is a PrepareS array, otherwise return 0.
//
// main.c
// pattern2
//
// Created by Suresh KUMAR Mukhiya on 7/11/14.
// Copyright (c) 2014 Suresh KUMAR Mukhiya. All rights reserved.
//
#include <stdio.h>
int isMadhavArray(int b[],int len)
{
int m = 0, n = sqrt(8*len+1)/2,flag = 1;
int sizeCheck = checkSize(len);
if(sizeCheck == 1)
{
flag = 1;
}
else{
flag = 0;
}
for(int i = 0; i<n; i ++)
{
int sum=0;
for(int j = 0; j<i+1; j++)
{
sum = sum + b[m];
m = m+ 1;
}
if(b[0] != sum)
{
flag = 0;
break;
}
}
return flag;
}
int main(int argc, const char * argv[])
{
//int b[] = {2,1,1};
//int b[] = {2,1,1,4,-1,-1};
// int b[] = {6,2,4,2,2,2,1,5,0,0};
//int b[] = {18,9,10,6,6,6};
//int b[] = {3,1,2,3,0};
//int b[] = {0,0,0,0,0,0,0,0,0,0,1,1,1,-2,-1};
int b[] = {-6,-3,-3,8,-5,-4};
int len = (sizeof(b)/sizeof(b[0]));
int r = isMadhavArray(b, len);
printf("isMadhavArray= %d\n",r);
return 0;
}
int checkSize(int n)
{
int trues = 1;
int number = 8*n+1;
int temp = sqrt(number);
if(temp * temp !=number)
{trues = 0;}
return trues;
}
Some Tracings:
2,1,1 = is PrepareS array, returns 1
2,1,1,4,-1,-1 is PrepareS array, returns 1
3,1,2,3,0 is NOT PrepareS Array, returns 0 because it does not satisfy n*(n+1)/2 length.
0 comments:
Feel free to contact the admin for any suggestions and help.