Friday, April 24, 2009

EasyProb

This is one of the Problems that I did long time ago but then I came back to it today. I had a text file containing the Result that had been generated using the Code though the Code was missing.
So, I had to start everything from scratch and I have become a bit Rusty though got it working in some time.

The Code for the Same ::



#include <iostream>
#include <fstream>
using namespace std;
/*
* String Uses a Recursive Function to Achieve the Effect.
*/
string ret(int a) {

/*
* Base Cases
*/
if (a <= 0)
return "";
else if (a == 1)
return "2(0)";
else if (a == 2)
return "2";
/*
* Recursive Step Begins here.
*/

else {
string s = "";
int count = 1;
while (a > 0) {
if (a % 2 == 1)
//Magic Statement
s = (count <= 2 ? ret(count) : "2(" + ret(count - 1) + ")")+(s == "" ? "" : "+") + s;
count++;
a /= 2;
}
return s;
}
}

int main() {
int a;
while (cin >> a)
cout << a << "=" << ret(a) << endl;
return 0;
}



It feels good to get such Codes working in real quick time ;) .
PS :
1) The Output for all The Inputs in the Problem::

137=2(2(2)+2+2(0))+2(2+2(0))+2(0)
1315=2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
73=2(2(2)+2)+2(2+2(0))+2(0)
136=2(2(2)+2+2(0))+2(2+2(0))
255=2(2(2)+2+2(0))+2(2(2)+2)+2(2(2)+2(0))+2(2(2))+2(2+2(0))+2(2)+2+2(0)
1384=2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2)+2(2(2)+2(0))+2(2+2(0))
16385=2(2(2+2(0))+2(2)+2)+2(0)

2) If you do have a code that is better than mine Please make it a point to post/Comment about it.

3 comments:

Tushar Chandra said...

#include
using namespace std;
string f(int n){
if(n==0) return "0";
string s = "";
for(int i=16;i>=0;i--){
s+=((1<<i)&n)==0 ? "" : ((i==1) ? "2+" : "2("+f(i)+")+");
}
return s.substr(0,s.length()-1);
}
int main(){
cout<<"137="<<f(137)<<endl;
cout<<"1315="<<f(1315)<<endl;
cout<<"73="<<f(73)<<endl;
cout<<"136="<<f(136)<<endl;
cout<<"255="<<f(255)<<endl;
cout<<"1384="<<f(1384)<<endl;
cout<<"16385="<<f(16385)<<endl;
return 0;
}

Tushar Chandra said...

Thanks for the code :) Helped me a lot

Unknown said...

hey there.
i want to know logic behind this problem. i studied your code but i'm not getting any clue.
can you plz elaborate in text.

thanks