Ζητούμενη λύση:
____________________________________________________
#include<iostream>
#include<iomanip>
#include "math.h"
using namespace std;
typedef unsigned long long ull ;
ull perfect(ull);
int main()
{
ull inputnumber, outputnumber ;
do {
cout<<"\nEnter a positive integer number: ";
cin>>inputnumber;
if (inputnumber>0)
outputnumber = perfect(inputnumber);
else
outputnumber = 0 ;
if (outputnumber > 0)
cout<<inputnumber<<" is a perfect square, with square root "<<outputnumber<< endl;
else
cout<< inputnumber<<" is NOT a perfect square...\n";
} while (inputnumber>0) ;
return 0;
}
ull perfect(ull a)
{
ull root_of_a, root_of_a_squared;
root_of_a = truncl(sqrtl(a)) ; // candidate root should not be altered by truncl
root_of_a_squared = root_of_a * root_of_a ;
if (root_of_a_squared == a ) // just found a perfect square!
return (root_of_a);
else
return 0;
}
_________________________________________________
Βέλτιστη λύση με χρήση μαθηματικών βιβλιοθηκών truncl(), sqrtl() , με διαφορετική υλοποίηση της function perfect()
Σημ: Θα μπορούσαν να χρησιμοποιηθούν και οι βιβλιοθήκες floor(), ceil()
****************************************************************************
ull perfect(ull a)
{
ull root_of_a, root_of_a_squared;
root_of_a = truncl(sqrtl(a)) ; // candidate root should not be altered by truncl
root_of_a_squared = root_of_a * root_of_a ;
if (root_of_a_squared == a ) // just found a perfect square!
return (root_of_a);
else
return 0;
}
*****************************************************************************
- Log in to post comments
Comments