1

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.

2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by nullptr
0

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;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.