Thread: What is wrong with this code of perfect number generation

  1. #16
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by megafiddle
    I am wondering if the sqrt function is guaranteed to return an integral value when the square root
    is a perfect divisor, eg, 1000.00000000 returned as sqrt of 1000000.

    It apparently worked in this case, but not sure if it always would.
    I think the answer is no due to floating point inaccuracy, but you can always add some small value to the result before casting to the integer type to avoid truncating to less than the integer square root.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  2. #17
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    The answer is no due to floating point inaccuracy (and the fact that floating point variables can't represent as many integral values as an integral type of the same or larger size).

    It's generally not a good idea to use sqrt() when working with integers, anyway. There are plenty of algorithms around for computing the integer square root (the largest integer which, when multiplied by itself, does not exceed the value).
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. perfect number
    By mallyg34 in forum C++ Programming
    Replies: 9
    Last Post: 04-03-2010, 02:20 PM
  2. Replies: 5
    Last Post: 10-05-2009, 10:21 AM
  3. What is perfect number
    By IPCHU in forum C Programming
    Replies: 5
    Last Post: 12-08-2006, 11:23 AM
  4. Perfect number...
    By Argo_Jeude in forum C++ Programming
    Replies: 8
    Last Post: 07-12-2005, 01:53 PM
  5. Perfect number
    By TheSki in forum C++ Programming
    Replies: 2
    Last Post: 10-30-2001, 04:34 PM

Tags for this Thread