so i have a problem
Mr. Dengklek wants to make a square pond for his ducks, with the following conditions:
The area of the pond is between 100,000 and 200,000 square cm. The area of the pond (in square cm) is an even number. The area of the pond (in square cm) is a perfect square. determine the area of the smallest pond that meets all of these requirements?
so my solution
#include <iostream>
#include <cmath>
using namespace std;
int main(){
for(int luas = 100000;luas <= 200000;luas++){
int akar = sqrt(luas);
if (luas % 2 == 0 && akar*akar == luas){
cout << luas << endl;
break;
}
}
}
What's on my mind is that the code has to fulfill that rule only if it fulfills it then break immediately, initially there was an error after asking GPT it turned out that it lacked #include <cmath>
it turned out that the real solution was without #include <cmath>
by using the concept of true false can anyone help me to make that code
If you don't want to use cmath
, you don't need to use std::sqrt
: if you loop on the square root directly (however, you will have to compute the square root of your lower value previously, as noted in comment) :
#include <iostream>
int main(){
// sqrt(100000) = 316.22..
for(int squareLength = 317;squareLength*squareLength <= 200000;squareLength++)
{
int luas = squareLength*squareLength;
if ( luas % 2 == 0){
std::cout << luas << '\n';
break;
}
}
}
On the other hand, if you consider that you can use cmath
, it's simpler :
#include <iostream>
#include <cmath>
int computeLowestPossibleValue(int lower, int upper)
{
int squareLength = static_cast<int>(std::ceil(std::sqrt(lower)));
int luas = squareLength*squareLength;
while(luas <= upper)
{
if ( luas % 2 == 0)
{
return luas;
}
squareLength++;
luas = squareLength*squareLength;
}
return -1;
}
int main()
{
int answer = computeLowestPossibleValue(100000, 200000);
if( answer != -1)
{
std::cout << answer << std::endl;
}
else
{
std::cout << "No value found in interval" << std::endl;
}
}
Here you can test it with a compiler : https://www.mycompiler.io/view/KFFMEwjXZ2R.