Sunday, July 26, 2009

Challenging Question for IT Only !!!?

Do it using C Language. So, I will check your answer in my Borland C. I will pick the best answer for the fastest and the right answer. Better fasten your seat belt !?





Find the Perfect Number.





Sample Number : 28


The factorial from 28 is : 1,2,4,7,14


If you multiple the factorial, you will get back the sample Number :


1+2+4+7+14 = 28.


That's called Perfect Number.





Sample input :


6


28





Sample output :


1,2,3


1,2,4,7,14

Challenging Question for IT Only !!!?
I shouldn't be doing this but.... This code will generate all perfect numbers from an interval which you place into the stdin (the console). For example if you want all perfect numbers from [1,1000] just type 1 1000. Here is the code:





#include %26lt;stdio.h%26gt;





bool perfect(int x){


int s=0;


for (int i=1;i%26lt;=(x/2)+1;i++)


if (x%i==0) s+=i;


if (s==x) return true;


return false;


}





void gen(int x){


for (int i=1;i%26lt;=(x/2)+1;i++)


if (x%i==0) printf("%d ",i);


printf("\n");


}





int main() {


int a,b;


scanf("%d %d",%26amp;a,%26amp;b);


if ((a*b%26lt;0) || (a%26gt;b)) {printf("Input error!"); return 1;}


for (int i=a;i%26lt;=b;i++)


if (perfect(i)) {printf("%d :",i); gen(i);}


return 0;


}





Be careful how you ask qusetions next time :). That's not multiplying.
Reply:THATS IT.....





..........U GOT IT!
Reply:huh
Reply:Certainly NOT gonna write in C. Would take some effort in VB, but I don't feel like doing it right now. Also, this is not necessarly for IT experts -- more for developers as most "IT experts" don't do a whole lot of C developing.
Reply:They're kinda called factors not factorials... Oh and you're excluding the number itself, which is always a factor of itself... But I'm gonna base it without the number itself... I'm guessing you mean a program that finds perfect numbers... so... Here it goes:





#include %26lt;cstdlib%26gt;


#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


#include %26lt;sstream%26gt;


using namespace std;





int findFactorsSum(int k)


{


int sum = 0;


for(int i = 1; i %26lt; k; ++i)


{


if(k%i==0)


{


sum+=i;


}


}


return sum;


}


int main(int argc, char *argv[])


{


if ( argc == 3)


{


istringstream buffer(argv[1]);


int start;


int end;


buffer %26gt;%26gt; start;


istringstream buffer2(argv[2]);


buffer2 %26gt;%26gt; end;


for(int i = start; i %26lt; end; ++i)


{


int sum = findFactorsSum(i);


if (sum == i)


{


cout %26lt;%26lt; i %26lt;%26lt; endl;


}


}


}


else


{


cout %26lt;%26lt; "Usage: pn %26lt;startingNo%26gt; %26lt;endingNo%26gt;" %26lt;%26lt; endl;


}


system("PAUSE");


return EXIT_SUCCESS;


}
Reply:You said multiple the factoral when actually you are adding the factorals
Reply:thats not a factorial e.g a factorial for 7 is 1*2*3*4*5*6*7





,


and thats adition not multiple(1+2+4+7+14)


No comments:

Post a Comment