Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
It is pretty much similar to generating fibonicci series . I used the same algorithm to generate the array of sum of square. Infact this can be modified to generate the array of sum/multiplication of square/cube.
package example.datastructure.interview;
import java.util.ArrayList;
/**
Given an integer N, populate an array of size N with the first N sum-of-squares.
In other words, if you were given N=3, your array would be [1, 5, 14] (1^2, 1^2 + 2^2, 1^2 + 2^2 + 3^2).
*/
public class FindSumOfSqaure {
/**
* @param args
*/
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
// sum of square for n=5;
for (int i=1; i <=5; i++)
{
list.add(new Integer(sumofSquare(i)));
}
System.out.println(list);
}
static int sumofSquare(int num)
{
if (num==1)
return 1;
return sumofSquare(num-1)+ num*num;
}
}
public static void main(String args[])
{
System.out.println("Enter the size of array:");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int a[] = new int[n], temp=0,j, sum=0;
for(int i=1,k=0;i<=n;i++,k++)
{
sum = sum + i*i;
a[k] = sum;
}
for (int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
Using recursion but the fibonacci concept
int a[100];
void sum_of_2(int a_index, int target)
{
if(a_index == target)
return;
a[a_index] = a[a_index-1] + (a_index+1)*(a_index+1);
printf("%d\n", a[a_index]);
sum_of_2(a_index+1, target);
}
int main()
{
memset(a, 0, 100*sizeof(int));
a[0] = 1;
sum_of_2(0, 100);
}
void PrintArray(int N, int count, int sum)
- DashDash April 24, 2013{
if(count > N)
return;
else
{
Sum = Sum + pow(count, 2);
printf("%d", Sum);
PrintArray(N, count+1, Sum);
}
}