1. Home
  2. Computing & Technology
  3. C / C++ / C#
photo of David Bolton
David's C / C++ / C# Blog

By David Bolton, About.com Guide to C / C++ / C#

Interesting C Puzzle

Thursday October 2, 2008
What does the following function do?

#include <stdio.h>

float puzzle( float inp )
{
  const float ths = 1.5F;
  const long k = 21*76069667;

  float a, b;
  int c;

  a = inp * 0.5F;
  b = inp;
  c = *( long *) &b;
  c = k - ( c >> 1 ) ;
  b = *( float *) &c;
  b = b * ( ths - ( a * b * b ) ) ;

  return 1/b;
}

Answer on Saturday!

Comments
October 3, 2008 at 2:35 am
(1) Oliver MK says:

I suppose it calculates “sqrt” approximately.

October 3, 2008 at 5:59 am
(2) Sumit Suman says:

The program will return the negative of the cube root of the ‘inp’ variable….!(approx. value)…
suppose we pass inp =2.4 from the main function,
then return value will be -0.076989

October 3, 2008 at 6:50 am
(3) raja says:

It returns the approximate square root of ‘inp’.

October 3, 2008 at 8:34 am
(4) Muhammad Ameen says:

It gives an approximation of the square root of inp. But I really can’t say how in the world does it work !!

October 21, 2008 at 11:56 pm
(5) Jot says:

The result of this program is undefined. It shall behave differently depending of the byte order of the processor, size of a float and size of a long.

December 22, 2008 at 4:15 am
(6) Limon says:

Very interesting problem. i have to think few time to get answer.
http://www.youngprogrammer.com

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

©2009 About.com, a part of The New York Times Company.

All rights reserved.