The goal of this program is to find all Pythagorean triples for each value (a, b, c) less than 500 using Euclid's formula (a = m^2 -n^2, b = 2mn, c = m^2 + n^2.) So here's my code.
int main()
{
clock_t start = clock()/ (CLOCKS_PER_SEC/1000);
for (int m = 1; m <= 500; m++)
{
for (int n = 1; n <= 500; n++)
{
int a = (m*m)-(n*n);
int b = 2*m*n;
int c = (m*m)+(n*n);
if (m > n && a + b == c)
{
cout << a << " + " << b << " = " << c << endl;
}
}
}
clock_t finish = clock()/ (CLOCKS_PER_SEC/1000);
cout << "completed in " <<clock() << " ms";
return 0;
}
I tried this and my output is nothing. The way I thought it'd work was: for every integer m less than/equal to 500 and starting at 1, add one to m each time. Same deal for n. Then plug those values into the formula and if a+b == c, it prints those values, thus finding my triples. But I'm not getting any output.
a + b = (m^2 + 2mn - n^2) = (m+n)^2 - 2n^2
c = m^2 + n^2 = (m+n)^2 - 2mn
You required a + b = c
--> 2n^2 = 2mn
--> m = n
Since you also required m > n, you cannot find any solution.
Your condition is wrong: you're trying to get
(m^2 - n^2) + 2mn = (m^2 + n^2)
(m - n)^2 = m^2 + n^2
but for n > 0 you will always have the following strict inequality:
(m - n)^2 < m^2 < m^2 + n^2
According to wikipedia, you wanted to check whether the sum of squares was equal -
(a^2 + b^2) == c^2
I figured out the problem; in the final iteration of the program I have to restrict c to <= 500:
int main()
{
clock_t start = clock()/ (CLOCKS_PER_SEC/1000);
for (int n = 1; n <= 500; n++)
{
for (int m = n+1; m <= 500; m++)
{
int a = (m*m)-(n*n);
int b = 2*m*n;
int c = (m*m)+(n*n);
if ((a*a) + (b*b) == (c*c) && c <= 500)
{
cout << a << " + " << b << " = " << c << endl;
}
}
}
clock_t finish = clock()/ (CLOCKS_PER_SEC/1000);
cout << "completed in " <<clock() << " ms";
return 0;
}
That way the program doesn't go long like I was having problems with. Thank you all!
You made a couple mistakes in your implementation (see fix below):
int main()
{
for (int n = 1; n <= 500; ++n) // note the swap for the loops
{
for (int m = n + 1; m <= 500 && (m*m + n*n) <= 500; ++m) // note that m starts at n + 1
{
int a = (m*m)-(n*n);
int b = 2*m*n;
int c = (m*m)+(n*n);
// Euclid already proved this, so there is no need to test it.
std::cout << a << " + " << b << " = " << c << std::endl;
}
}
return 0;
}
Euclid's formula requires m > n, so there is no need to check values that don't meet that criteria
Your test (a + b) == c will never work anyway. The formula is a^2 + b^2 = c^2 - that does not mean a + b = c.
Related
Problem is :
Write a function that as an input argument receives a three-digit positive number and as a result has to get the sum between the largest and the smallest number obtained by the same 3 digits divided by the median digit.
Example: input argument to function 438
The largest with the same digits is 843, the smallest is 348, so it should be calculated (843 + 348) / 4.
I have tried it and got the result ok but my code seems to complicated so iam asking is there a better way to do it?
Thanks in advance
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int check(int x) {
int a, b, c, biggestNum, smallestNum, medianNum;
a = x / 100;
b = (x / 10) % 10;
c = x % 10;
if (a > b && a > c && b > c) {
biggestNum= a * 100 + b * 10 + c;
smallestNum= c * 100 + b * 10 + a;
medianNum= b;
}
else if (a > b && a > c && b < c) {
biggestNum= a * 100 + c * 10 + b;
smallestNum= b * 100 + c * 10 + a;
medianNum= c;
}
else if (b > a && b > c && a < c) {
biggestNum= b * 100 + c * 10 + a;
smallestNum= a * 100 + c * 10 + b;
medianNum= c;
}
else if (b > a && b > c && a > c) {
biggestNum= b * 100 + a * 10 + c;
smallestNum= c * 100 + a * 10 + b;
medianNum= a;
}
else if (c > a && c > b && a > b) {
biggestNum= c * 100 + a * 10 + b;
smallestNum= b * 100 + a * 10 + c;
medianNum= a;
}
else if (c > a && c > b && a < b) {
biggestNum= c * 100 + b * 10 + a;
smallestNum= a * 100 + b * 10 + c;
medianNum= b;
}
cout << "Smallest number is: " << smallestNum<< " ,biggest is: " << biggestNum << " and median is: " << medianNum<< "." << endl;
return (biggestNum + smallestNum) / medianNum;
}
int main() {
cout << "Enter one 3 digit positive number: ";
int x;
cin >> x;
float result = check(x);
cout << "The result is: " << result << "." << endl;
system("pause");
return 0;
}
The posted code can't really produce the right answer, considering that the result is calculated with integer arithmetic:
int check(int x) // <- note the type of the returned value
{
int biggestNum, smallestNum, medianNum;
// ...
return (biggestNum + smallestNum) / medianNum; // <- This is an integer division
}
int main()
{
int x;
// ...
float result = check(x); // Now it's too late to get the right result
}
The logic also doesn't consider all the possible cases, as a matter of fact it ignores duplicated digits and the big if else if construct, lacking a default branch (a final unconditioned else), leaves those uninitialized variables undetermined so that the following operation gives a meaningless result.
Given the assignment restrictions, I'd write something like the following
#include <utility>
// The assignment is about 3-digit numbers, you should check that x is actually in
// the range [100, 999]. Note that one of the extremes is a special case.
// Well, both, actually.
double I_ve_no_idea_how_to_name_this(int x)
{
constexpr int base = 10;
int smallest = x % base;
x /= base;
int median = x % base;
x /= base;
// Note that this "works" (extracting the third digit) even if
// x isn't a 3-digit number. If you can assure the input is well
// defined, you can simplify this.
int biggest = x % base;
// Now we can sort the previous variables.
using std::swap;
if ( median < smallest ) {
swap(median, smallest);
}
// Now I know that smallest <= median
if ( biggest < median ) {
swap(biggest, median);
}
// Now I know that median <= biggest
// ...
// Is that enough or am I missing something here?
// Please think about it before running the code and test it.
// Once the variables are sorted, the result is easily calculated
return (biggest + smallest + base * (2 * median + base * (biggest + smallest)))
/ static_cast<double>(median);
}
First, you should use more descriptive variable names and should initialize each variable on definition. These two steps help greatly in squashing bugs in complex programs. I know this one isn't complex, but it's a good habit to have. Second, the standard library can help with finding the largest and smallest digit, which then makes the rest simple. So here's an example without any if statements.
Finally, using namespace std; is a bad practice and should be avoided.
double check(int x)
{
int a = x / 100;
int b = (x / 10) % 10;
int c = x % 10;
int bigdigit = std::max({ a, b, c }); // find largest
int smalldigit = std::min({ a, b, c }); //find smallest
int middledigit = a + b + c - bigdigit - smalldigit; // sum of all digits minus largest and smallest gives the remaining one
int biggest = smalldigit + middledigit * 10 + bigdigit * 100;
int smallest = smalldigit * 100 + middledigit * 10 + bigdigit;
std::cout << "biggest: " << biggest << '\n';
std::cout << "smallest: " << smallest << '\n';
std::cout << "median: " << middledigit << '\n';
return (1.0 * biggest + 1.0 * smallest) / (1.0 * middledigit); --using double instead of int, as result could be fractional
}
try this...
int check(int x) {
int a,b,c,temp;
a = x/100;
b = (x/10)%10;
c = x%10;
if(b>a){
temp=a;
a=b;
b=temp;
}
if(c>b){
temp=b;
b=c;
c=temp;
}
if(b>a){
temp=a;
a=b;
b=temp;
}
cout << "smallest: " << a+(b*10)+(c*100) << "\n";
cout << "biggest: " << (a*100)+(b*10)+c << "\n";
cout << "median: " << b << "\n";
return (((a+c)*100)+(2*b*10)+(a+c))/b;
}
check this check function.
int check(int x) {
if(x >= 1000) x %= 1000; //or return -1;
//get digits
int M = x/100;
int C = (x/10)%10;
int m = x%10;
//unrolled bubble sort.
if(M < C) swap(M,C);
if(C < m) swap(C,m);
if(M < C) swap(M,C);
//simplified formula
return ((m+M)*(101))/C + 20;
}
//derivation of formula
B = M*100 + C*10 + m;
s = m*100 + C*10 + M;
B+s = (m+M)*100 + C*20 + (m+M)
= (m+M)*(100 + 1) + C*20
(B+s)/C = ((m+M)*(100 + 1) + C*20)/C
= ((m+M)*(101))/C + 20
I'm having trouble compiling this program with #include. I see that if I comment out this line it compiles.
MatrixXd A = (1.0 / (double) d) * (p * U * p.transpose() - (p * u) * (p * u).transpose()).inverse();
I am unable to change the header since I need to run this code in ROS and I have to use the Eigen library built within. I am using the code as described in this link
How to fit a bounding ellipse around a set of 2D points.
Any help is greatly appricated.
pound include iostream
pound include Eigen/Dense
using namespace std;
using Eigen::MatrixXd;
int main ( )
{
//The tolerance for error in fitting the ellipse
double tolerance = 0.2;
int n = 12; // number of points
int d = 2; // dimension
MatrixXd p(d,n); //Fill matrix with random points
p(0,0) = -2.644722;
p(0,1) = -2.644961;
p(0,2) = -2.647504;
p(0,3) = -2.652942;
p(0,4) = -2.652745;
p(0,5) = -2.649508;
p(0,6) = -2.651345;
p(0,7) = -2.654530;
p(0,8) = -2.651370;
p(0,9) = -2.653966;
p(0,10) = -2.661322;
p(0,11) = -2.648208;
p(1,0) = 4.764553;
p(1,1) = 4.718605;
p(1,2) = 4.676985;
p(1,3) = 4.640509;
p(1,4) = 4.595640;
p(1,5) = 4.546657;
p(1,6) = 4.506177;
p(1,7) = 4.468277;
p(1,8) = 4.421263;
p(1,9) = 4.383508;
p(1,10) = 4.353276;
p(1,11) = 4.293307;
cout << p << endl;
MatrixXd q = p;
q.conservativeResize(p.rows() + 1, p.cols());
for(size_t i = 0; i < q.cols(); i++)
{
q(q.rows() - 1, i) = 1;
}
int count = 1;
double err = 1;
const double init_u = 1.0 / (double) n;
MatrixXd u = MatrixXd::Constant(n, 1, init_u);
while(err > tolerance)
{
MatrixXd Q_tr = q.transpose();
cout << "1 " << endl;
MatrixXd X = q * u.asDiagonal() * Q_tr;
cout << "1a " << endl;
MatrixXd M = (Q_tr * X.inverse() * q).diagonal();
cout << "1b " << endl;
int j_x, j_y;
double maximum = M.maxCoeff(&j_x, &j_y);
double step_size = (maximum - d - 1) / ((d + 1) * (maximum + 1));
MatrixXd new_u = (1 - step_size) * u;
new_u(j_x, 0) += step_size;
cout << "2 " << endl;
//Find err
MatrixXd u_diff = new_u - u;
for(size_t i = 0; i < u_diff.rows(); i++)
{
for(size_t j = 0; j < u_diff.cols(); j++)
u_diff(i, j) *= u_diff(i, j); // Square each element of the matrix
}
err = sqrt(u_diff.sum());
count++;
u = new_u;
}
cout << "3 " << endl;
MatrixXd U = u.asDiagonal();
MatrixXd A = (1.0 / (double) d) * (p * U * p.transpose() - (p * u) * (p * u).transpose()).inverse();
MatrixXd c = p * u;
cout << A << endl;
cout << c << endl;
return 0;
}
If I replace the obvious pound include bogus by
#include <iostream>
#include <Eigen/Dense>
it compiles just fine. It also runs, prints some numbers and returns 0.
I need to generate 4 random numbers, each between [-45 +45] degrees. and if rand%2 = 0 then I want the result (the random number generated to be equal to -angle). Once the 4 random numbers are generated it is requires to scan these angles and find a lock (the point at which the angles meet). Also -3,-2,-1,... +3 in the loop in if statement indicate that the lock takes place within 6 degrees beamwidth. the code works. But can it be simplified? also The objective is to establish a lock between 2 points by scannin elevation and azimuth angles at both points.
#include <iostream>
#include <conio.h>
#include <time.h>
using namespace std;
class Cscan
{
public:
int gran, lockaz, lockel;
};
int main()
{
srand (time(NULL));
int az1, az2, el1, el2, j, k;
BS1.lockaz = rand() % 46;
BS1.lockel = rand() % 46;
BS2.lockaz = rand() % 46;
BS2.lockel = rand() % 46;
k = rand() % 2;
if(k == 0)
k = -1;
BS1.lockaz = k*BS1.lockaz;
k = rand() % 2;
if(k == 0)
k = -1;
BS1.lockel = k*BS1.lockel;
k = rand() % 2;
if(k == 0)
k = -1;
BS2.lockaz = k*BS2.lockaz;
k = rand() % 2;
if(k == 0)
k = -1;
BS2.lockel = k*BS2.lockel;
for(az1=-45; az1<=45; az1=az1+4)
{
for(el1=-45; el1<=45; el1=el1+4)
{
for(az2=-45; az2<=45; az2=az2+4)
{
for(el2=-45; el2<=45; el2=el2+4)
{
if((az1==BS1.lockaz-3||az1==BS1.lockaz-2||az1==BS1.lockaz-1||az1==BS1.lockaz||az1==BS1.lockaz+1||az1==BS1.lockaz+2||az1==BS1.lockaz+3)&&
(az2==BS2.lockaz-3||az2==BS2.lockaz-2||az2==BS2.lockaz-1||az2==BS2.lockaz||az2==BS2.lockaz+1||az2==BS2.lockaz+2||az2==BS2.lockaz+3)&&
(el1==BS1.lockel-3||el1==BS1.lockel-2||el1==BS1.lockel-1||el1==BS1.lockel||el1==BS1.lockel+1||el1==BS1.lockel+2||el1==BS1.lockel+3)&&
(el2==BS2.lockel-3||el2==BS2.lockel-2||el2==BS2.lockel-1||el2==BS2.lockel||el2==BS2.lockel+1||el2==BS2.lockel+2||el2==BS2.lockel+3))
{
cout << "locked \n" << BS1.lockaz << " " << BS1.lockel << " " << BS2.lockaz << " " << BS2.lockel <<endl
< az1 << " " << el1 << " " << az2 << " " << el2 << endl;
k = 1;
break;
}
if(k==1)
break;
}
if(k==1)
break;
}
if(k==1)
break;
}
if(k==1)
break;
}
_getch();
}
BS1.lockaz = rand() % 91 - 45;
BS1.lockel = rand() % 91 - 45;
BS2.lockaz = rand() % 91 - 45;
BS2.lockel = rand() % 91 - 45;
Integer angles in degrees? Very questionable. Something "physical" like an angle is normally best expressed as a floating-point number, so I'd first change
typedef double angle;
struct Cscan { // why class? This is clearly POD
int gran; //I don't know what gran is. Perhaps this should also be floating-point.
angle lockaz, lockel;
};
That seems to make it more difficult at first sight because neither the random-range-selection with % works anymore nor is it much use to compare floats for equality. Which is, however, a good thing, because all of this is in fact very bad practise.
If you want to keep using rand() as the random number generator (though I'd suggest std::uniform_real_distribution), write a function to do this:
const double pi = 3.141592653589793; // Let's use radians internally, not degrees.
const angle rightangle = pi/2.; // It's much handier for real calculations.
inline angle deg2rad(angle dg) {return dg * rightangle / 90.;}
angle random_in_sym_rightangle() {
return rightangle * ( ((double) rand()) / ((double) RAND_MAX) - .5 );
}
Now you'd just do
BS1.lockaz = random_in_sym_rightangle();
BS1.lockel = random_in_sym_rightangle();
BS2.lockaz = random_in_sym_rightangle();
BS2.lockel = random_in_sym_rightangle();
Then you need to do this range-checking. That's again something to put in a dedicated function
bool equal_in_margin(angle theta, angle phi, angle margin) {
return (theta > phi-margin && theta < phi+margin);
}
Then you do this exhaustive search for locks. This could definitely be done more efficiently, but that's an algorithm issue and has nothing to do with the language. Sticking to the for loops, you can still make them look much nicer by avoiding this explicit break checking. One way is good old goto, I'd propose here you just stick it in an extra function and return when you're done
#define TRAVERSE_SYM_RIGHTANGLE(phi) \
for ( angle phi = -pi/4.; phi < pi/4.; phi += deg2rad(4) )
int lock_k // better give this a more descriptive name
( const Cscan& BS1, const Cscan& BS2, int k ) {
TRAVERSE_SYM_RIGHTANGLE(az1) {
TRAVERSE_SYM_RIGHTANGLE(el1) {
TRAVERSE_SYM_RIGHTANGLE(az2) {
TRAVERSE_SYM_RIGHTANGLE(el2) {
if( equal_in_margin( az1, BS1.lockaz, deg2rad(6.) )
&& equal_in_margin( el1, BS1.lockel, deg2rad(6.) )
&& equal_in_margin( az2, BS1.lockaz, deg2rad(6.) )
&& equal_in_margin( el2, BS2.lockel, deg2rad(6.) ) ) {
std::cout << "locked \n" << BS1.lockaz << " " << BS1.lockel << " " << BS2.lockaz << " " << BS2.lockel << '\n'
<< az1 << " " << el1 << " " << az2 << " " << el2 << std::endl;
return 1;
}
}
}
}
}
return k;
}
I'm working on problem 9 in Project Euler:
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
The following code I wrote uses Euclid's formula for generating primes. For some reason my code returns "0" as an answer; even though the variable values are correct for the first few loops. Since the problem is pretty easy, some parts of the code aren't perfectly optimized; I don't think that should matter. The code is as follows:
#include <iostream>
using namespace std;
int main()
{
int placeholder; //for cin at the end so console stays open
int a, b, c, m, n, k;
a = 0; b = 0; c = 0;
m = 0; n = 0; k = 0; //to prevent initialization warnings
int sum = 0;
int product = 0;
/*We will use Euclid's (or Euler's?) formula for generating primitive
*Pythagorean triples (a^2 + b^2 = c^2): For any "m" and "n",
*a = m^2 - n^2 ; b = 2mn ; c = m^2 + n^2 . We will then cycle through
*values of a scalar/constant "k", to make sure we didn't miss anything.
*/
//these following loops will increment m, n, and k,
//and see if a+b+c is 1000. If so, all loops will break.
for (int iii = 1; m < 1000; iii++)
{
m = iii;
for (int ii = 1; n < 1000; ii++)
{
n = ii;
for (int i = 1; k <=1000; i++)
{
sum = 0;
k = i;
a = (m*m - n*n)*k;
b = (2*m*n)*k;
c = (m*m + n*n)*k;
if (sum == 1000) break;
}
if (sum == 1000) break;
}
if (sum == 1000) break;
}
product = a * b * c;
cout << "The product abc of the Pythagorean triplet for which a+b+c = 1000 is:\n";
cout << product << endl;
cin >> placeholder;
return 0;
}
And also, is there a better way to break out of multiple loops without using "break", or is "break" optimal?
Here's the updated code, with only the changes:
for (m = 2; m < 1000; m++)
{
for (int n = 2; n < 1000; n++)
{
for (k = 2; (k < 1000) && (m > n); k++)
{
sum = 0;
a = (m*m - n*n)*k;
b = (2*m*n)*k;
c = (m*m + n*n)*k;
sum = a + b + c;
if ((sum == 1000) && (!(k==0))) break;
}
It still doesn't work though (now gives "1621787660" as an answer). I know, a lot of parentheses.
The new problem is that the solution occurs for k = 1, so starting your k at 2 misses the answer outright.
Instead of looping through different k values, you can just check for when the current sum divides 1000 evenly. Here's what I mean (using the discussed goto statement):
for (n = 2; n < 1000; n++)
{
for (m = n + 1; m < 1000; m++)
{
sum = 0;
a = (m*m - n*n);
b = (2*m*n);
c = (m*m + n*n);
sum = a + b + c;
if(1000 % sum == 0)
{
int k = 1000 / sum;
a *= k;
b *= k;
c *= k;
goto done;
}
}
}
done:
product = a * b * c;
I also switched around the two for loops so that you can just initialize m as being larger than n instead of checking every iteration.
Note that with this new method, the solution doesn't occur for k = 1 (just a difference in how the loops are run, this isn't a problem)
Presumably sum is supposed to be a + b + c. However, nowhere in your code do you actually do this, which is presumably your problem.
To answer the final question: Yes, you can use a goto. Breaking out of multiple nested loops is one of the rare occasions when it isn't considered harmful.
I was reading through How can I write a power function myself? and the answer given by dan04 caught my attention mainly because I am not sure about the answer given by fortran, but I took that and implemented this:
#include <iostream>
using namespace std;
float pow(float base, float ex){
// power of 0
if (ex == 0){
return 1;
// negative exponenet
}else if( ex < 0){
return 1 / pow(base, -ex);
// even exponenet
}else if ((int)ex % 2 == 0){
float half_pow = pow(base, ex/2);
return half_pow * half_pow;
//integer exponenet
}else{
return base * pow(base, ex - 1);
}
}
int main(){
for (int ii = 0; ii< 10; ii++){\
cout << "pow(" << ii << ".5) = " << pow(ii, .5) << endl;
cout << "pow(" << ii << ",2) = " << pow(ii, 2) << endl;
cout << "pow(" << ii << ",3) = " << pow(ii, 3) << endl;
}
}
though I am not sure if I translated this right because all of the calls giving .5 as the exponent return 0. In the answer it states that it might need a log2(x) based on a^b = 2^(b * log2(a)), but I am unsure about putting that in as I am unsure where to put it, or if I am even thinking about this right.
NOTE: I know that this might be defined in a math library, but I don't need all the added expense of an entire math library for a few functions.
EDIT: does anyone know a floating-point implementation for fractional exponents? (I have seen a double implementation, but that was using a trick with registers, and I need floating-point, and adding a library just to do a trick I would be better off just including the math library)
I have looked at this paper here which describes how to approximate the exponential function for double precision. After a little research on Wikipedia about single precision floating point representation I have worked out the equivalent algorithms. They only implemented the exp function, so I found an inverse function for the log and then simply did
POW(a, b) = EXP(LOG(a) * b).
compiling this gcc4.6.2 yields a pow function almost 4 times faster than the standard library's implementation (compiling with O2).
Note: the code for EXP is copied almost verbatim from the paper I read and the LOG function is copied from here.
Here is the relevant code:
#define EXP_A 184
#define EXP_C 16249
float EXP(float y)
{
union
{
float d;
struct
{
#ifdef LITTLE_ENDIAN
short j, i;
#else
short i, j;
#endif
} n;
} eco;
eco.n.i = EXP_A*(y) + (EXP_C);
eco.n.j = 0;
return eco.d;
}
float LOG(float y)
{
int * nTemp = (int*)&y;
y = (*nTemp) >> 16;
return (y - EXP_C) / EXP_A;
}
float POW(float b, float p)
{
return EXP(LOG(b) * p);
}
There is still some optimization you can do here, or perhaps that is good enough.
This is a rough approximation but if you would have been satisfied with the errors introduced using the double representation, I imagine this will be satisfactory.
I think the algorithm you're looking for could be 'nth root'. With an initial guess of 1 (for k == 0):
#include <iostream>
using namespace std;
float pow(float base, float ex);
float nth_root(float A, int n) {
const int K = 6;
float x[K] = {1};
for (int k = 0; k < K - 1; k++)
x[k + 1] = (1.0 / n) * ((n - 1) * x[k] + A / pow(x[k], n - 1));
return x[K-1];
}
float pow(float base, float ex){
if (base == 0)
return 0;
// power of 0
if (ex == 0){
return 1;
// negative exponenet
}else if( ex < 0){
return 1 / pow(base, -ex);
// fractional exponent
}else if (ex > 0 && ex < 1){
return nth_root(base, 1/ex);
}else if ((int)ex % 2 == 0){
float half_pow = pow(base, ex/2);
return half_pow * half_pow;
//integer exponenet
}else{
return base * pow(base, ex - 1);
}
}
int main_pow(int, char **){
for (int ii = 0; ii< 10; ii++){\
cout << "pow(" << ii << ", .5) = " << pow(ii, .5) << endl;
cout << "pow(" << ii << ", 2) = " << pow(ii, 2) << endl;
cout << "pow(" << ii << ", 3) = " << pow(ii, 3) << endl;
}
return 0;
}
test:
pow(0, .5) = 0.03125
pow(0, 2) = 0
pow(0, 3) = 0
pow(1, .5) = 1
pow(1, 2) = 1
pow(1, 3) = 1
pow(2, .5) = 1.41421
pow(2, 2) = 4
pow(2, 3) = 8
pow(3, .5) = 1.73205
pow(3, 2) = 9
pow(3, 3) = 27
pow(4, .5) = 2
pow(4, 2) = 16
pow(4, 3) = 64
pow(5, .5) = 2.23607
pow(5, 2) = 25
pow(5, 3) = 125
pow(6, .5) = 2.44949
pow(6, 2) = 36
pow(6, 3) = 216
pow(7, .5) = 2.64575
pow(7, 2) = 49
pow(7, 3) = 343
pow(8, .5) = 2.82843
pow(8, 2) = 64
pow(8, 3) = 512
pow(9, .5) = 3
pow(9, 2) = 81
pow(9, 3) = 729
I think that you could try to solve it by using the Taylor's series,
check this.
http://en.wikipedia.org/wiki/Taylor_series
With the Taylor's series you can solve any difficult to solve calculation such as 3^3.8 by using the already known results such as 3^4. In this case you have
3^4 = 81 so
3^3.8 = 81 + 3.8*3( 3.8 - 4) +..+.. and so on depend on how big is your n you will get the closer solution of your problem.
I and my friend faced similar problem while we're on an OpenGL project and math.h didn't suffice in some cases. Our instructor also had the same problem and he told us to seperate power to integer and floating parts. For example, if you are to calculate x^11.5 you may calculate sqrt(x^115, 10) which may result more accurate result.
Reworked on #capellic answer, so that nth_root works with bigger values as well.
Without the limitation of an array that is allocated for no reason:
#include <iostream>
float pow(float base, float ex);
inline float fabs(float a) {
return a > 0 ? a : -a;
}
float nth_root(float A, int n, unsigned max_iterations = 500, float epsilon = std::numeric_limits<float>::epsilon()) {
if (n < 0)
throw "Invalid value";
if (n == 1 || A == 0)
return A;
float old_value = 1;
float value;
for (int k = 0; k < max_iterations; k++) {
value = (1.0 / n) * ((n - 1) * old_value + A / pow(old_value, n - 1));
if (fabs(old_value - value) < epsilon)
return value;
old_value = value;
}
return value;
}
float pow(float base, float ex) {
if (base == 0)
return 0;
if (ex == 0){
// power of 0
return 1;
} else if( ex < 0) {
// negative exponent
return 1 / pow(base, -ex);
} else if (ex > 0 && ex < 1) {
// fractional exponent
return nth_root(base, 1/ex);
} else if ((int)ex % 2 == 0) {
// even exponent
float half_pow = pow(base, ex/2);
return half_pow * half_pow;
} else {
// integer exponent
return base * pow(base, ex - 1);
}
}
int main () {
for (int i = 0; i <= 128; i++) {
std::cout << "pow(" << i << ", .5) = " << pow(i, .5) << std::endl;
std::cout << "pow(" << i << ", .3) = " << pow(i, .3) << std::endl;
std::cout << "pow(" << i << ", 2) = " << pow(i, 2) << std::endl;
std::cout << "pow(" << i << ", 3) = " << pow(i, 3) << std::endl;
}
std::cout << "pow(" << 74088 << ", .3) = " << pow(74088, .3) << std::endl;
return 0;
}
This solution of MINE will be accepted upto O(n) time complexity
utpo input less then 2^30 or 10^8
IT will not accept more then these inputs
It WILL GIVE TIME LIMIT EXCEED warning
but easy understandable solution
#include<bits/stdc++.h>
using namespace std;
double recursive(double x,int n)
{
// static is important here
// other wise it will store same values while multiplying
double p = x;
double ans;
// as we multiple p it will multiply it with q which has the
//previous value of this ans latter we will update the q
// so that q has fresh value for further test cases here
static double q=1; // important
if(n==0){ ans = q; q=1; return ans;}
if(n>0)
{
p *= q;
// stored value got multiply by p
q=p;
// and again updated to q
p=x;
//to update the value to the same value of that number
// cout<<q<<" ";
recursive(p,n-1);
}
return ans;
}
class Solution {
public:
double myPow(double x, int n) {
// double q=x;double N=n;
// return pow(q,N);
// when both sides are double this function works
if(n==0)return 1;
x = recursive(x,abs(n));
if(n<0) return double(1/x);
// else
return x;
}
};
For More help you may try
LEETCODE QUESTION NUMBER 50
**NOW the Second most optimize code pow(x,n) **
logic is that we have to solve it in O(logN) so we devide the n by 2
when we have even power n=4 , 4/2 is 2 means we have to just square it (22)(22)
but when we have odd value of power like n=5, 5/2 here we have square it to get
also the the number itself to it like (22)(2*2)*2 to get 2^5 = 32
HOPE YOU UNDERSTAND FOR MORE YOU CAN VISIT
POW(x,n) question on leetcode
below the optimized code and above code was for O(n) only
*
#include<bits/stdc++.h>
using namespace std;
double recursive(double x,int n)
{
// recursive calls will return the whole value of the program at every calls
if(n==0){return 1;}
// 1 is multiplied when the last value we get as we don't have to multiply further
double store;
store = recursive(x,n/2);
// call the function after the base condtion you have given to it here
if(n%2==0)return store*store;
else
{
return store*store*x;
// odd power we have the perfect square multiply the value;
}
}
// main function or the function for indirect call to recursive function
double myPow(double x, int n) {
if(n==0)return 1;
x = recursive(x,abs(n));
// for negatives powers
if(n<0) return double(1/x);
// else for positves
return x;
}