Hello,

I am writing a C++ program to find the largest such number such that the square root of that number is less than or equal to a fixed number, set by me, like this:

``````#include <stdio.h>
#include <math.h>
int main (void)
{
long fixed, param, result;
result = 0;
param = 1;
fixed = 20;
while (result < fixed) {
result = sqrt(param);
param++;
}
param -= 1;
printf ("%d\n", param);
return 0;
}``````

This works fine as is, but the trouble is that my fixed is a number between 10^6 and 3 * 10^15, so this code is not optimal for computing values on such large scale. What can be done to increase efficiency?

Thank you.

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by ItecKid

Hello,

I am writing a C++ program to find the largest such number such that the square root of that number is less than or equal to a fixed number, set by me, like this:

``````#include <stdio.h>
#include <math.h>
int main (void)
{
long fixed, param, result;
result = 0;
param = 1;
fixed = 20;
while (result < fixed) {
result = sqrt(param);
param++;
}
param -= 1;
printf ("%d\n", param);
return 0;
}``````

This works fine as is, but the trouble is that my fixed is a number between 10^6 and 3 * 10^15, so this code is not optimal for computing values on such large scale. What can be done to increase efficiency?

Thank you.

Why bother taking a square root? Why not just square the fixed number?:

``````int fixed = 20;
int largest = fixed * fixed;  // 400``````

I had to stare at your reply for several minutes before realizing that that is a much better, faster way to solve my problem...thank you.

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.