Find the nearest integer that has a whole number square root

This is a discussion on Find the nearest integer that has a whole number square root within the C Programming forums, part of the General Programming Boards category; I need to write a program that will ask for a number, and then print out the nearest integer that ...

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    43

    Find the nearest integer that has a whole number square root

    I need to write a program that will ask for a number, and then print out the nearest integer that has a whole number square root. Its supposed to be able to handle numbers up to 10 digits.

    So if I entered 8, it would give me 9. 68 gives me 64, etc.

    I'm lost as to how I should approach comparing the input number to the nearest squared integer. Can anyone give me some tips on the basic logic here?

    Thanks in advance,
    crazychile

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,566
    If your number lies between two perfect squares, it's square root will lie between the square root of those perfect squares. For example, 68 lies between 64 and 81. It's square root is 8.25, which is between 8 and 9.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Posts
    43
    Thanks.

    I should have asked that differently. How would you find the next lowest perfect square and the next highest?. I think I can manage the compare once I get those.

    thank you,
    crazychile

  4. #4
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,249
    How was Anduril's answer not the answer?

    The square root of 68 is about 8.25. Thus, the nearest perfect square to 68 is either 8^2 or 9^2, i.e. 64 or 81. Which one is closer to 68?
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  5. #5
    Registered User
    Join Date
    Sep 2008
    Posts
    43
    I think I get ya now. I was stuck on finding the nearest integer that was a perfect square, instead of taking the square root and going up or down one from there and then squaring it.

    Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. code to find th square root of a number
    By CODY21 in forum C++ Programming
    Replies: 34
    Last Post: 10-29-2010, 09:27 AM
  2. Memory Leak in AppWizard-Generated Code
    By jrohde in forum Windows Programming
    Replies: 4
    Last Post: 05-19-2010, 04:24 PM
  3. Replies: 8
    Last Post: 12-23-2009, 12:55 PM
  4. program to calculate the square root
    By saszew in forum C Programming
    Replies: 7
    Last Post: 10-28-2008, 12:53 PM
  5. square root of a number in C
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-19-2001, 04:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21