cubic function root bisection search time limit exceeded - c++

I have implemented this solution for finding a root of a cubic function
f(x) = ax3 + bx2 + cx + d
given a, b, c, and d, ensuring it's being monotonic.
After submitting the solution to an online judge without being shown the test cases, I am being faced by a time limit error. a, b, c, and d guarantee that the function is monotonic and we know it is being continuous. The code first finds the interval [A, B] such that f(A) * f(B) < 0; then the code moves to implement the bisection search.
What I want to know is if there is some possibility to minimize the time complexity of my code so it passes the online judge. The input is a, b, c, d, and the output should be the root with an error 0.000001.
Code:
#include <iostream>
#include <algorithm>
//#include <cmath>
//#include <string>
using namespace std;
int f(double a, double b, double c, double d, double x) {
return x*(x*(a*x + b) + c) + d;
}
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
double a, b, c, d, A, B, x = 1, res;
cin >> a >> b >> c >> d;
//determinning the interval
double f_x = f(a, b, c, d, x);
if (a > 0) { // strictly increasing
if (f_x > 0) { B = 0;
while (f(a, b, c, d, x) >= 0) { x -= x; }
A = x; }
else { A = 0;
while (f(a, b, c, d, x) <= 0) { x += x; }
B = x; }
}
else { //strictly decreasing
if (f_x > 0) { A = 0;
while (f(a, b, c, d, x) >= 0) { x += x; }
B = x; }
else { B = 0;
while (f(a, b, c, d, x) <= 0) { x -= x; }
A = x; }
}
// Bisection Search
double l = A;
while ((B - A) >= 0.000001)
{
// Find middle point
l = (A + B) / 2;
// Check if middle point is root
if (f(a, b, c, d, l) == 0.0)
break;
// Decide the side to repeat the steps
else if (f(a, b, c, d, l)*f(a, b, c, d, A) < 0)
B = l;
else
A = l;
}
res = l;
cout.precision(6);
cout << fixed << " " << res;
return 0;
}

There is no need to determine the initial interval, just take [-DBL_MAX, +DBL_MAX]. The tolerance can be chosen to be 1 ULP.
The following code implements these ideas:
// This function will be available in C++20 as std::midpoint
double midpoint(double x, double y) {
if (std::isnormal(x) && std::isnormal(y))
return x / 2 + y / 2;
else
return (x + y) / 2;
}
int main() {
...
const auto fn = [=](double x) { return x * (x * (x * a + b) + c) + d; };
auto left = -std::numeric_limits<double>::max();
auto right = std::numeric_limits<double>::max();
while (true) {
const auto mid = midpoint(left, right);
if (mid <= left || mid >= right)
break;
if (std::signbit(fn(left)) == std::signbit(fn(mid)))
left = mid;
else
right = mid;
}
const double answer = left;
...
}
Initially, fn(x) can overflow and return inf. No special handling of this case is needed.

Related

How can I make this inverse modulo program take in larger numbers?

Heres the code:
int gcdExtended(int a, int b, int* x, int* y);
void modInverse(int A, int M)
{
int x, y;
int g = gcdExtended(A, M, &x, &y);
if (g != 1)
cout << "Inverse doesn't exist";
else {
int res = (x % M + M) % M;
cout << "Modular multiplicative inverse is " << res;
}
}
int gcdExtended(int a, int b, int* x, int* y)
{
// Base Case
if (a == 0) {
*x = 0, *y = 1;
return b;
}
// To store results of recursive call
int x1, y1;
int gcd = gcdExtended(b % a, a, &x1, &y1);
*x = y1 - (b / a) * x1;
*y = x1;
return gcd;
}
I'm not sure how to take in bigger numbers like 15001 (mod 5729413260) without getting overflow. Should I not use recursion? I tried long long but that didn't work, any suggestions?
You might change int to long long; if that's not sufficient, then boost::multiprecision might help.

printing the closest pair of points

I was writing this code to find the minimum distance between 2 points.The code I have written gives me the minimum distance correctly but does not give the correct coordinates from which the minimum distance is computed.Kindly help me identify the problem according to me this is the correct approach to print the points as well along with the minimum distance.
#include<bits/stdc++.h>
#define FOR(i,N) for(int i=0;i<(N);i++)
#define rep(i,a,n) for(int i=(a);i<(n);i++)
using namespace std;
struct point {
int x;
int y;
};
typedef struct point point;
void printarr(point arr[], int n) {for(int i = 0; i < n; i++) cout <<
arr[i].x << " " << arr[i].y << endl; cout << endl;
bool comparex(const point& X, const point& Y) { return X.x < Y.x; }
bool comparey(const point& X, const point& Y) { return X.y < Y.y; }
float getdis(point X, point Y) { return sqrt((X.x - Y.x)*(X.x - Y.x) + (X.y
- Y.y)*(X.y - Y.y)); }
float brutedis(point P[], int n, point A[]) {
float d = INT_MAX;
float temp;
FOR(i, n) {
rep(j, i+1, n) {
temp = getdis(P[i],P[j]);
if(temp < d) {
d = temp;
A[0].x = P[i].x; A[0].y = P[i].y;
A[1].x = P[j].x ; A[1].y = P[j].y;
}
}
}
return d;
}
float stripdis(point P[], int n, float d, point A[]) {
float temp = d;
float dis;
sort(P, P + n, comparey);
FOR(i, n) {
rep(j,i+1,n) {
if(abs(P[j].y - P[i].y) < d) {
dis = getdis(P[j], P[i]);
if(dis < temp) {
temp = dis;
A[0].x = P[i].x; A[0].y = P[i].y;
A[1].x = P[j].x ; A[1].y = P[j].y;
}
}
}
}
return temp;
}
float solve(point P[], int n, point A[]) {
if(n <= 3) return brutedis(P, n, A);
int mid = n/2;
point M = P[mid];
float d = min(solve(P, mid, A), solve(P+mid, n-mid, A));
point strip[n];
int j = 0;
int i = 0;
while(i < n) {
if(abs(P[i].x - M.x) < d) strip[j++] = P[i];
i++;
}
return min(d, stripdis(strip, j, d, A));
}
int main() {
point P[] = {{0, 0}, {-4,1}, {-7, -2}, {4, 5}, {1, 1}};
int n = sizeof(P) / sizeof(P[0]);
sort(P, P+n, comparex);
point A[2];
cout << "Minimum Distance = " << solve(P, n, A) << "\n";
printarr(A, 2);
//printarr(P, n);
return 0;
}
To the extent I can follow your badly formatted code, brutedis unconditionally modifies A[] and it gets called again after you have found the right answer (but don't know you found the right answer).
So if the first call were best in min(solve(P, mid, A), solve(P+mid, n-mid, A)); the second could still call brutedis and destroy A[]
You call solve twice, both giving it A as the parameter. Each of these calls always overwrite A, but only one returns the correct answer. And they both call brutedis that also always overwrites A.
The easiest way to fix this is to introduce an additional parameter to all these functions, that would contain the minimal distance found so far, the same way you did with stripdis.
float solve(point P[], int n, float d, point A[]) {
if(n <= 3) return brutedis(P, n, d, A);
...
d = solve(P, mid, d, A);
d = solve(P+mid, n-mid, d, A);
d = stripdis(strip, j, d, A));
...
float brutedis(point P[], int n, float d, point A[])
{
// float d = INT_MAX -- Not needed
Thus A will only be overeritten if the distance between the new pair of points is globally minimal so far.
No need to call min as each function already keeps the minimum of d and the distance it finds.
That is because after getting the correct coordinates in "A" array, you are again updating that. just look for the below statement in your code:
float d = min(solve(P, mid, A), solve(P+mid, n-mid, A));
this will give correct minimum distance but not correct coordinates. Just think about it, if your first call to solve, in the above statement has the minimum distance coordinates, then your second call is going to modify the coordinates in A[]. take a pen and paper and try to solve for the coordinates you have, it'll give you better understanding.

getNthRoots function wrong answers

So i have a function
Vector getNthRoots(double a, double b, double c, int n)
{
Vector v;
int i;
v.length = 0;
double m, a2, b2, c2;
if (n % 2 == 0)
{
a2 = a;
b2 = b;
c2 = c;
if (a<0)
a2 = a*(-1);
if (b<0)
b2 = b*(-1);
if (c<0)
c2 = c*(-1);
m = floor(pow(max(a2, b2, c2),1/n));
for (i = 1; i <= m; i++)
if (pow(i, n) >= min(a2, b2, c2) && pow(i, n) <= max(a2, b2, c2))
{
v.values[v.length] = i;
v.length++;
v.values[v.length] = (-1)*i;
v.length++;
}
return v;
}
else {
for (i = ceil(pow(min(a, b, c),1/n)); i <= floor(pow(max(a, b, c),1/n)); i++)
if (pow(i, n) >= min(a, b, c) && pow(i, n) <= max(a, b, c))
{
v.values[v.length] = i;
v.length++;
}
return v;
}
}
This function is supposed to give you the numbers at power n (number^n) which are in the interval of min(a,b,c) and max(a,b,c);
Other functions/headers
double max(double a, double b, double c)
{
if (a >= b && a >= c)
return a;
if (b >= a && b >= c)
return b;
if (c >= a && c >= b)
return c;
return a;
}
double min(double a, double b, double c)
{
if (a <= b && a <= c)
return a;
if (b <= a && b <= c)
return b;
if (c <= a && c <= b)
return c;
return a;
}
#include <iostream>
#include <cmath>
using namespace std;
#define MAX_ARRAY_LENGTH 100
struct Vector
{
unsigned int length;
int values[MAX_ARRAY_LENGTH];
};
It seems i can`t receive the good answer . For example
for getNthRoots(32,15,37,5) it should return a vector [2] because 2^5 =32 which belongs to interval [15,37] but i don`t receive anything
or getNthRoots(32,1,7,5) it should return a vector [1,2] but i only receive 1 as answer
I am guessing here is the problem for (i = ceil(pow(min(a, b, c),1/n)); i <= floor(pow(max(a, b, c),1/n)); i++)but i don`t know how i could fix it
1/n evaluates to 0, because it is evaluated as an integer expression. Try replacing all the "1/n"s with "1.0/n"s.
Take care to handle the case where n is 0.

Return from Recursion (c/c++)

I'm having trouble returning a desired value in a recursive call. I want it to always return 0 unless a certain condition is met, in that case it should return 1 and exit.
int check = recursion(a, b, c, d, e, f);
int recursion(int *a, int *b, int c, int d, int e, int f){
int k, dX, dY;
for(k=0;k<=b[1]-1;k++){
dX = b[k*4+3] - e;
dY = b[k*4+2] - f;
if(((dX == 1 || dX == -1) && (dY == 0))){
if(b[k*4+4] == 1) return 1;
e = b[k*4+3];
f = b[k*4+2];
b[k*4+2] = b[k*4+3] = 0;
recursion(a, b, c, d, e, f);
}
if(((dY == 1 || dY == -1) && (dX == 0))){
if(b[k*4+4] == 1) return 1;
e = b[k*4+3];
f = b[k*4+2];
b[k*4+2] = b[k*4+3] = 0;
recursion(a, b, c, d, e, f);
}
}
return 0;
}
A lot of irrelevant information has been removed, but as you can see if b[k*4+4] == 1 at anypoint, check should then equal 1. Otherwise, return 0 and check will = 0. It completes a basic traversal, which I know is completing correctly and is even stopping at the terminating condition (b[k*4+4] == 1) but it isn't returning the correct value.
Currently, it is ALWAYS returning 0. Check always equals 0, although it is stopping once the condition is met. I also tried removing the ending return 0; although check still equals zero...
You just need to check the return values of your recursive calls, i.e.,
return recursion(a, b, c, d, e, f);
You need to do return recursion(a, b, c, d, e, f); instead of just recursion(a, b, c, d, e, f);. Otherwise, the result of those recursive calls will be lost.
edit: to not prematurely exit your loop, you can do this:
int check = recursion(a, b, c, d, e, f);
int recursion(int *a, int *b, int c, int d, int e, int f){
int k, dX, dY;
for(k=0;k<=b[1]-1;k++){
dX = b[k*4+3] - e;
dY = b[k*4+2] - f;
if(((dX == 1 || dX == -1) && (dY == 0))){
if(b[k*4+4] == 1) return 1;
e = b[k*4+3];
f = b[k*4+2];
b[k*4+2] = b[k*4+3] = 0;
if(recursion(a, b, c, d, e, f) == 1)
return 1;
}
if(((dY == 1 || dY == -1) && (dX == 0))){
if(b[k*4+4] == 1) return 1;
e = b[k*4+3];
f = b[k*4+2];
b[k*4+2] = b[k*4+3] = 0;
if(recursion(a, b, c, d, e, f) == 1)
return 1;
}
}
return 0;
}

how do i implement the bisection method using this function prototype in C++

double p1::root(double (*pf)(double k), int a, int b, double e)
im not sure how to go about it, i understand that i have to loop that pinpoints the midpoint and such
double p1::root(double (*pf)(double k), int a, int b, double e) {
// void nrerror(char error_text[]);
int j;
float dx, f, fmid, xmid, rtb;
f = (*pf)(a);
fmid = (*pf)(b);
//if (f*fmid >= 0.0) nrerror("root must be bracketed for bisection in rtbis")\
;
rtb = f < 0.0 ? (dx=b-a,a) : (dx=a-b,b);
for(j = 1;j <40; j++) {
fmid = (*pf)(xmid = rtb+(dx *= .5));
if (fmid <= 0.0) rtb = xmid;
if (fabs(dx) < e || fmid == 0.0) return rtb;
}
// nrerror("too many bisections in rtbis");
return 0.0;
}
double p1::test_function(double k) {
return (pow(k, 3) -2);
}
then in main i have this
double (*pf)(double k);
pf = &p1::test_function;
//double result = p1::root(pf, a, b, e);
Maybe Numerical Recipes will give you an idea. Hint: it's recursive.