Dear All,

I have written a program that finds the integer whose square is closest to but greater than the integer number input as data. But it is giving me an erroneous answer. My algorithm is:

  1. Select a number which is half the input number.
  2. Square it and check whether it satisfies our condition.
  3. Subtract one and square it and check whether it satisfies our condition.
  4. Repeat 2 and 3 iteratively until a solution is obtained.

Below is my code for the above problem.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
    int n,m,input,powm,pown;
    printf("Enter a number");
    scanf("%d",&input);
    m=input/2;
    n=m-1;
    powm=pow(m,2);
    pown=pow(n,2);
    if (powm>input)
    {
          if(pown>input)
          {
          m=m-1;
          n=n-1;
          powm=pow(m,2);
          pown=pow(n,2);
          }
    }

    printf("The integer whose square is closest to but greater than the input number is %d",n);

    system("pause");
    return 0;
}

Thank you for your reply.

Here's an implementation of your algorithm in c++.

int BestSquareMatch(int i)
{
    if (i == 0) return 0;
    if (i < 0) return -1; // error undefined

    int match = i/2;
    while (pow(static_cast<double>(match), 2) > i)
    {
        --match;
    }
    //increment to the last integer that satisfied the condition
    return ++match;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.