PRATIAN Interview Question
Java DevelopersCountry: India
Interview Type: Written Test
c#, 2 variants.
using System;
namespace DisplaySeries {
class Program {
// Variant 1
static private void DisplaySeriesV1( int n ) {
for ( int i = 0; i <= n; i++ ) {
var res = (i + 2) * (2 * i * i - i + 3) / 6;
Console.Write($"{res} ");
}
}
// Variant 2
static private void DisplaySeriesV2( int n ) {
var prev = 1;
for (int i = 0; i <= n; i++) {
var res = prev + i * i;
prev = res;
Console.Write($"{res} ");
}
}
static void Main(string[] args)
{
DisplaySeriesV1(10);
Console.WriteLine();
DisplaySeriesV2(10);
Console.ReadLine();
}
}
}
Two examples. First time through I misread the prompt and thought they only wanted N, so I derived a summation formula based on looking up the i^2 one. I then realized it was asking for the whole series, so an alternative that uses an accumulator is listed as well. Both run in O(n) and use O(1) space, and the alternate might end up being a hair faster due to fewer mathematical operations.
int[] computeUpToNInSeries(int n) {
final int[] series = new int[n];
for (int i = 1; i <= n; i++) {
series[i - 1] = compute(i);
}
return series;
}
int compute(int i) {
return (i * (i - 1) * (2*i - 1)) / 6 + 1;
}
int[] alternateComputeUpToNInSeries(int n) {
final int[] series = new int[n];
int accumulator = 1;
for (int i = 1; i <= n; i++) {
series[i - 1] = accumulator;
accumulator += i * i;
}
return series;
}
//Ques=>Write the code to display the series 1 ,2,6,15,31,56....N
#include<stdio.h>
int main()
{
int nofterm,addprevious,i,value ;
addprevious=1;
printf("How many terms do u want to print");
scanf("%d",&nofterm);
for(i=0;i<nofterm;i++)
{
value=addprevious+i*i;
addprevious=value;
printf("%d->", value);
}
return 0;
}
c++, implementation
- kyduke December 10, 2015