Nutanix Interview Question
Software DevelopersCountry: United States
Interview Type: Phone Interview
Analysis.
The problem is that of :
1 + 3 + 5 + ...
That is sum of n odd numbers.
That is known to be : 9math.com/book/sum-first-n-odd-natural-numbers
=> n^2.
Thus we are to find, if the number given is a perfectly square no. or not.
Now, given we do not want to use square root, which is
a terribly complex operation, we can do as follows:
[ careercup.com/question?id=14797683 ]
"""
To make a pyramid
the first row will have 1 *
the second row will have 3 *
the third row will have 5 *
the N th row will have 1+3+5+7. (expand sequence to have N terms )
The sum or first n odd numbers is n*n
For forming a pyramid with N *s - N should be a perfect square
"""
import math
def isPyramidPossible (n):
root = int (math.sqrt(n))
return int (root) == n //root
def main(n):
print (f'A pyramid with {n} *s is {"" if isPyramidPossible(n) else "not"} possibe')
if (__name__== "__main__"):
for i in range (1, 100):
main (i)
since first row will have 1 star 2nd row 3 star 3rd row 5 star so on.
so to make n row you should have total star equal to sum of first n odd numbers.
As you can see above first n odd number form Arithematic progression with difference of 2
sum of n numbers of an Arithematic progression =(n* (2*a+(n-1)*d))/2
where n = number of term
a(first term) = 1
d(difference) = 2
so sum = (n*(2*1+(n-1)*2)/2 = n*n = n^2
so you simply have to check number of star is perfect square or not.
Output:
- ProTechMulti October 19, 2017Input: 4, Possible: true
Input: 9, Possible: true
Input: 6, Possible: false