Algorithm


problem Link : https://onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1282 

Solve the equation: p ∗ e −x + q ∗ sin(x) + r ∗ cos(x) + s ∗ tan(x) + t ∗ x 2 + u = 0 where 0 ≤ x ≤ 1. Input Input consists of multiple test cases and terminated by an EOF. Each test case consists of 6 integers in a single line: p, q, r, s, t and u (where 0 ≤ p, r ≤ 20 and −20 ≤ q, s, t ≤ 0). There will be maximum 2100 lines in the input file. Output For each set of input, there should be a line containing the value of x, correct up to 4 decimal places, or the string ‘No solution’, whichever is applicable.

Sample Input 0 0 0 0 -2 1 1 0 0 0 -1 2 1 -1 1 -1 -1 1

Sample Output 0.7071 No solution 0.7554

Code Examples

#1 Code Example with C Programming

Code - C Programming

#include <bits/stdc++.h>
using namespace std;

int p,q,r,s,t,u;

double f(double mid){
    return p*exp(-mid)+q*sin(mid)+r*cos(mid)+s*tan(mid)+t*mid*mid+u;
}

int main() {
    while(scanf("%d %d %d %d %d %d",&p,&q,&r,&s,&t,&u) != EOF){
// Given f(x) = 0:
// Since f is a non-increasing function on [0,1],
// it is sufficient to check the signs for f(0) and f(1) to determine whether
// there is a root in range [0,1]. 
        if(f(0)*f(1) > 0) printf("No solution\n");
        else {
            double lo = 0, hi = 1;
            while((hi-lo) > 0.0000001){
                double mid = (lo+hi)/2;
                double val = f(mid);
                // raising x, decreases our val
                if(val > 0) lo = mid;
                else hi = mid;
            }
            printf("%.4f\n",lo);
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
0 0 0 0 -2 1
1 0 0 0 -1 2
1 -1 1 -1 -1 1

Output

x
+
cmd
0.7071
No solution
0.7554
Advertisements

Demonstration


UVA Online Judge solution - 10341 - Solve It -  UVA Online Judge solution in C,C++,java

Previous
UVA Online Judge solution - 10340-All in All - UVA Online Judge solution in C,C++,java
Next
UVA Online Judge solution - 10344-23 out of 5 - UVA Online Judge solution in C,C++,java