n 1 2 3 4 5 6 7 8 9 10 11 12
f(n) 1 2 2 3 3 4 4 4 5 5 5 6
now the question was to develop a program to generate this sequence for a given 'n'taking time factors into consideration. As we can all see, there are some repetition sequences already there. but i envisaged a different set of patterns to generate the code for this series. First of all, we can see thatfor every n that is a perfect square, the f(n) is an odd numberwhich can be depicted as i + 2 if i = 1 for n = 1.
e.g. : when n=1, f(n)= 1.
when n=4, f(n)= 3. and so on...
Secondly, f(n) at a value of 'n' that is a perfect square repeats itself square root(n) number of times.
Lastly, between two 'n' values that are perfect squares there are larger square - (smaller square + 1) values of 'n' and f(n).
Now, thats all one needs to know to develop a very efficient solution to this problem. Here i present mine written in C++ language. though i agree that i have not added comments but still you can make it out easily.Lastly i will agree that though this code is not the shortest one (there is infact a three line code that can use three for() loops instead) but certainly this is the one with the shortest time complexity :
#include
class abc{
private :
int per_sq(int u)
{
int x;
for(x=1;x<=u;x++)
{
if((u-(x*x))==0)
return x;
}
return 0;
}
int near_sq(int v)
{
do{
v++;
}while(per_sq(v)>0);
return v;
}
void golomb(int a)
{
int i, j, k, c;
i = 0;j = 1;
for(j=1;j<=a;)
{
c = per_sq(j);
if(c>0)
{
i++;
for(k=0;k
{
if(j<=a)
{
cout <<>
j++;
}
else
break;
}
}
else
{
i++;
for(k=0;k
{
if(j<=a)
{
cout << i ;
j++;
}
else
break;
}
}
}
}
public :
void get()
{
int n;
cout << "Enter the value of n : ";
cin >> n;
golomb(n);
}
};
void main()
{
abc obj;
obj.get();
}