write code to find square-root using bisection method in c++? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Bisection is as far as i know narrowing your search and reach the specific value in interval. please give me a sample of that how to make a generic code to find square-root. the way i think is taking three variables low, mid, high. high = userinput, low = 0, mid (low + high) /2, problem is how to how to change values then.

#include <iostream>
using namespace std;
int main() {
int val;
cout << "Enter the number: ";
cin >> val;
if( val< 0) {
cout<< "According to my maths its not possible." << endl;
} else {
float low = 0, high = val;
float mid = (low + high)/2;
int c = 0;
while (c != 1) {
if(mid * mid = val) {
cout << "Square root is: " << mid <<endl;
c = 1;
} else {
if(mid * mid > val) {
high = mid;
mid = (low + high)/2;
} else {
low = mid;
mid = (low + high)/2;
}
}
}
}
return 0;
}

Lets say the we are looking for sqrt(N)
As described here, you have to find the average of LOW and HIGH, if square of average is greater than N, we change the high value with the average we just found, if it is less than N, we change the low value with the average. And we repeat the steps as many times to satisfy the required precision.

Related

Strong number problem in C++ but something is wrong with my code [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 days ago.
Improve this question
I'm coding for the Strong number problem and when I run it, i passed 3 cases. But when I run 4th case nothing happens.
I passed: 1, 2, 145 but 40585.
Here is my code:
#include <iostream>
using namespace std;
int Get(int n);
int Factorial(int n, int sum);
int main()
{
system("cls");
int n;
cout << "Enter. \n";
cin >> n;
if (n == Get(n))
{
cout << "True. \n";
}
else
{
cout << "False. \n";
}
return 0;
}
int Get(int n)
{
static int sum = 0;
if (n / 10)
{
Get (n / 10);
}
return sum += Factorial(n % 10, 1);
}
int Factorial(int n, int sum)
{
if (n == 1)
{
return sum;
}
else
{
return Factorial(n - 1, sum *= n);
}
}
I don't know why, so pls help me !
The problem is that in this line:
return sum += Factorial(n % 10, 1);
You call Factorial with n % 10 which can be 0.
This is not handled well by Factorial (it will recurse infinitely with negative values for n).
You can fix it by changing the recursion stop condition in Factorial to:
if (n <= 1)
{
// ...
}
A side note:
If you can implement a function using iteration (i.e. loops) instead of recursion - this is usually recommended. This is because recursion uses the stack which is usually relatively small.
For calculating factorial you have to cope with an additional issue of int overflowing very fast - 13! is already too big to be stored in a 32 bit integer. You can handle it by e.g. using a 64 bit integer or some big number library for bigger values.
However - in this specific case since the Factorial is calculated for a max value of 9 both issues are OK (although I would still prefer using one simple loop for factorial).
As #lastchance commented, you can also keep all the required 10 values (for 0! .. 9!) in a precalculated array.

C++: Could someone help me optimize my solution? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Program adds 2 fractions and displays their sum in a reduced form (n times). Could someone help me optimize my solution (According to SPOJ, the time limit has been exceeded)
My solution:
#include <iostream>
using namespace std;
int main()
{
int n, a, b, c, d, gcd;
long long num, den;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> a >> b >> c >> d;
num = (a*d)+(b*c);
den = b*d;
for(int j = 1; j <= num && j <= den; ++j)
{
if(num % j == 0 && den % j == 0)
{
gcd = j;
}
}
cout << num/gcd << " " << den/gcd << endl;
}
}
The key step in your code is computing the greatest common divisor of num and den. The code does this by testing every number less than or equal to either of them to find the largest that divides both. While this is a correct algorithm, it is very slow, requiring time proportional to whichever is smaller.
To make this faster, use the Euclidean algorithm, which takes time proportional to the logarithm of the smaller number, which means it is much faster. The essence of this algorithm is to divide one number by the other and replace the larger with the resulting remainder until that remainder is zero. Concretely, copying and slightly reformatting the code from tutorialspoint.com:
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
Alternatively, as noted in a comment by #badfilms, C++17 contains std::gcd in the library.

Too many recursive calls or too many cout? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Prints specific sequence by given n. For example n=1: 1, n=2: 121, n=3,1213121, n=4: 121312141213121 and so on. But for n > 11 the program stops working after 3556 cout. I think the problem is too many cout or too many recursive calls, but im not sure how to fix it or even is that really the problem. Please let me know if u have any solutions. Thank you so much!
#include <iostream>
using namespace std;
int findNumberByIndex(int index, int& number, int n) {
if (index < 0) {
return 0;
}
if (index % 2 == 0) {
return 1;
}
if (index == ((int)pow(2, number - 1) - 1)) {
return number;
}
index -= (int)pow(2, number);
findNumberByIndex(index, number, n);
}
int printSeq(int rowLen, int& index, int& number, int n, int& counter) {
if (index == rowLen) {
return 0;
}
int result = findNumberByIndex(index, number, n);
if (result == 0) {
number++;
}
else {
cout << result;
index++;
number = 2;
}
printSeq(rowLen, index, number, n, ++counter);
}
int main()
{
int n, index = 0, number = 2, seqLen = 1;
cin >> n;
int counter = 0;
if (n < 0 || n >= 20) {
return 0;
}
int rowLen = ((int)pow(2, n - 1) + (int)pow(2, n - 1) - 1);
printSeq(rowLen, index, number, n, counter);
cout << endl;
return 0;
}
In the definition of findNumberByIndex, you forgot to
return findNumberByIndex(index, number, n);
In the definition of printSeq, you forgot to
return printSeq(rowLen, index, number, n, ++counter);
This leads to undefined behaviour.
Regarding your hypothesis
I think the problem is too many cout or too many recursive calls
Unless specific concerns you can revoke the idea of "too many output". You could suffer from a too deep recursive call tree, but in your specific example your functions are tail-recusrive. With optimization correctly turned on, any decent compiler should optimize them.

Error in program to find the Armstrong numbers between intervals given by the user [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Error:
//Count(variable) not declared! error.
But I have declared it. This is a program to calculate the number of Armstrong digits in the interval given by the user. It will continue to run until there is at least one Armstrong number in the interval. I have used a Do-While loop for this purpose.
C++:
#include<iostream>
#include<cmath>
using namespace std;
//Function to check if the number is an Armstrong number
bool Armstrong(int n) {
int number, original, remainder, result = 0, k = 0;
original = n;
//Calculating the number of digits
while (original != 0) {
original /= 10;
++k;
}
original = n;
while (original != 0) {
remainder = original % 10;
result += pow(remainder, k);
original /= 10;
}
if (result == n)
return true;
else
return false;
}
//Checking Armstrong in the interval
int main() {
do {
int start, stop, n, i = 1;
std::cout << "Enter Starting Point: ";
std::cin >> start;
std::cout << "Enter Stop Point: ";
std::cin >> stop;
n = start;
int count = 0; //printing the numbers in the interval
for (; start <= stop; start++) {
if (Armstrong(start)) {
std::cout << "Armstrong Number " << i << " : " << start;
count++;
i++;
}
n--;
}
//It is showing the error here. "Count not Declared"
}
while (count == 0);
}
The problem is that you declare int count; inside the do-while loop, so you can't check for it in the loop condition. Move it to outside of the loop:
int count = 0;
do {
int start, stop, n, i = 1;
...
} while (count == 0);

Need help in avoiding 'Wrong Answer' on SPOJ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Problem : http://www.spoj.com/problems/EGYPIZZA/
I've been trying to solve this 'PIZZA' problem for quite some time and I have tried many, many
inputs and it seems to be working fine on my machine but the online judge keeps refusing to accept mu code saying its the wrong answer!!
Please help me out...
Here's my code:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char str[4],b[3][4]= {"1/4","1/2","3/4"};
unsigned int n, s = 1, count1 = 0, count2 = 0, count3 = 0;
scanf("%u",&n);
while(n--)
{
cin>>str;
if(strcmp(str,b[0])==0)
count2++;
else if(strcmp(str,b[1])==0)
count1++;
else if(strcmp(str,b[2])==0)
count3++;
}
while(count3!=0 && count2!=0)
{
count2--; count3--; s++;
}
if(count1%2!=0)
if(count2/2!=0)
{
count2-=2; count1--; s++;
}
s = s + (count1/2) + (count1%2) + (count2/4) + (count2%4) + count3 ;
printf("%u\n",s);
return 0;
}
EDIT :
I have updated my code after your suggestions please check it out guys!!
Still giving wrong answer..
Accepted Solution:
#include<iostream>
using namespace std;
int main()
{
string s;
int n, sum = 1, count1 = 0, count2 = 0, count3 = 0, extra;
cin >> n;
for (int i=0; i < n; i++)
{
cin >> s;
if (s == "1/2")count1 ++;
if (s == "1/4")count2 ++;
if (s == "3/4")count3 ++;
}
sum += count3 + count1/2.0 + 0.5;
extra = count3 + (count1%2)*2;
if (count2 >= extra)
{
count2 -= extra;
sum += count2 / 4.0 + 0.75;
}
cout << sum << endl;
return 0;
}
This problem would be more interesting if aboTrika don't insist on having his pizza one piece as the others. :)
Your program has numerous problems, such as using vectors where simple counters will suffice, and using floating point where integer arithmetic is appropriate. Perhaps the most serious problem is the statement s = s + q/4 + h/2 which in effect satisfies most requests for 1/4 pizza by grouping quarter-pizzas together and grouping half-pizzas together. Instead, requests for 1/4 pizza should be used first to complement as many 3/4-pizza requests as possible, then to fill up a 1/2-pizza request if the requested number of halves is odd, and only then used together.