Tuesday, September 25, 2007

One of the assignments given to us for the coding contest.....

Hey, here is one of the assignments that we were given in the C/C++ coding contests. Check it out and suggest any optimization, suggestions, anything....

Code:

/* This program calculates the value of a mathematical function and gives */
/* the output depending on it. The function is defined as follows :- */
/* f(1) = 1 */
/* f(2n) = n */
/* f(2n+1) = f(n) + f (n+1) */
/* The inputs should be taken till a negative value is inputed. */
/* The maximum number of inputs is considered to be 100. */

#include<iostream>

#define _maxInputs 100

using namespace std;

float Function(int);

main()
{
int* inNumberArray = new int[_maxInputs];
float* outAnswerArray = new float[_maxInputs];
int cnt, counter;

cout << endl;
cout << "Please enter the variable values. Enter negative value to exit";
cout << endl;

for(counter = 0; counter < _maxInputs; counter++)
{
cin >> inNumberArray[counter];

if(inNumberArray[counter] < 0)
break;

outAnswerArray[counter] = Function(inNumberArray[counter]);

}

cnt = counter;

for(counter = 0; counter < cnt; counter++)
{
cout << "F(" << inNumberArray[counter] << ") = "
<< outAnswerArray[counter] << "." << endl;

}

delete[] inNumberArray;
delete[] outAnswerArray;

return 0;

}

float Function (int inNumber)
{
if(inNumber == 1)
return 1.0;

else if(inNumber % 2 == 0)
return (inNumber/2.0);

else if(inNumber % 2 == 1)
return (Function((inNumber-1)/2) + Function((inNumber+1)/2));

}


Output:

EXECUTING:
/home/aditya/Mathematical-Function-1
----------------------------------------------

Please enter the variable values. Enter negative value to exit
1 2 3 4 5 6 7 8 9 10 11 12 -1
F(1) = 1.
F(2) = 1.
F(3) = 2.
F(4) = 2.
F(5) = 3.
F(6) = 3.
F(7) = 4.
F(8) = 4.
F(9) = 5.
F(10) = 5.
F(11) = 6.
F(12) = 6.

----------------------------------------------
Program exited successfully with errcode (0)
Press the Enter key to close this terminal ...

No comments: