calculating sqare root without use of square root function in c++ [closed] - c++

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 8 years ago.
Improve this question
You are required to write your own algorithm for computing square root. Write a
pseudocode rst before you go on and write the C++ program. Do not use the
sqrt function from the math library to compute the square root. Create your own
square root algorithm.
2. Your program should cater for all non-perfect square numbers as well as negative
integers that the user inputs. In these cases the program should prompt the user
that a perfect square has not been entered.
3. The program should allow the user three chances to enter a perfect square. If the
user is not able to enter a perfect square within the three chances then the program
should exit.
4. You are to use functions in your C++ program. Create a user dened function
by the name sqroot. This should be the function where you implement your own
square root algorithm. This function should return an integer and accept only one
input argument, that too of type integer.
i have tried but got stuck pliz help
#include <iostream>
#include <cmath>
#include <math.h>
#include <stdlib.h>
using namespace std;
int main (){
int test;
int square;
int answer;
int i=0;
cout << "enter a perfect sqare ";
cin >> square;
answer = pow(square, 0.5);
test = square % answer;
if (test==0){
cout << "the square is: " << answer;
}
if (test!=0){
cout << "enter a perfect sqare ";
cin >> square;
answer = pow(square, 0.5);
test = square % answer;
cout << "the square is: " << answer;
}
return 0;
}

See Newton-Raphson algorithm.
From Wikipedia: "a method for finding successively better approximations to the roots (or zeroes) of a real-valued function".
Lets say you are trying to find the root of 'a'.
Then basically, you are trying to find the roots of the function:
f(x) = x^2 - a
Also this method is known to be very fast.

If you really want to impress da' Prof, you could use the binomial expansion approximation with a power of 1/2:
=
a is the next perfect square from your input number (I'm sure it'll be easy for you to compute that, and its square root). Sub it into the formula, with x as your input number, not forgetting to use floating point variables for the fractions, and do what you like with the answer (in your case round it to an integer).
I know it's only an approximation but it should be more than good enough for integer answers.
http://en.wikipedia.org/wiki/Binomial_theorem

Related

Recursive function, geometric progression [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I've just started learning C++ and I came across a simple problem but couldn't solve. Help me please,
In geometric progression, b1=2, r=3.
Create recursive function that outputs initial n sequences of progression. n should be input.
Assuming b1 is the initial number and r is the multiplier (ratio?), that would give 2, 6, 18, 54, ....
The pseudo-code for such a beast would be:
def geometric (limit, current, multiplier):
if limit <= 0: return
print(current)
geometric(limit - 1, current * multiplier, multiplier)
def main():
b1 = 2
r = 3
n = input("How many terms? ")
geometric(n, b1, r)
The reason it's pseudo-code is that I tend to prefer for educational questions since people learn a lot more by converting it rather than just being given an answer.
So, in terms of how the recursive function works, you pass it the number of terms remaining along with the current term and the multiplier.
Provided it hasn't reached its base case (number of terms remaining is zero), it prints the current term then recursively calls itself, adjusting the arguments so as to approach the base case.
Once it has reached the base case, it will return (from all recursive levels).
Turning that into C++ is an exercise I'll leave for the reader, but I can provide something similar so you will see the approach taken.
Let's say you wanted to sum all the numbers between 1 and a given number. It has the same features as any recursive solution, including the one posed in your question:
an operation that can be defined in terms of a simpler operation; and
the base case.
In C++, a complete program to do that would be something like:
#include <iostream>
void recurse(int number, int sum) {
// Base case for printing and returning.
if (number <= 0) {
std::cout << "Sum is " << sum << '\n';
return;
}
// Recurse to next level.
recurse(number - 1, sum + number);
}
int main() {
int myNum;
std::cout << "Enter your number: ";
std::cin >> myNum;
recurse(myNum, 0);
}
Some sample runs:
Enter your number: 3
Sum is 6
Enter your number: 4
Sum is 10
Enter your number: 5
Sum is 15
Enter your number: 6
Sum is 21
Enter your number: 100
Sum is 5050
The explanatory text on your specific question, along with the C++ code showing how to do it for a different question, should hopefully be enough for you to work it out.

Calculate the payment [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 8 years ago.
Improve this question
double total,grandtotal;
double amount, change=0;
total=day* price* noRoom;
grandtotal=total*1.16;
cout<<"\t\tPlease enter your amount:RM";
cin>>amount;
while (amount < grandtotal)
{
cout << "\t\tPlease enter a valid amount:RM";
cin >> amount;
}
change=amount-grandtotal;
if (amount > grandtotal)
{
cout<<"\t\tYour change is: "<<change <<endl;
cout<<"\t\tThank You, Have a nice day! \n";
cout<<"\t\t Please come again \n";
}
else if( amount == grandtotal) //why this statement can't run if my amount is also equal to the grandtotal???
{
cout<<"\t\tThank You, Have a nice day! \n";
cout<<"\t \tPlease come again \n";
}
Your else if might be executed but most likely it won't happen, because double values precision is relatively high so there will be difference.
If you set the precision smaller for example that should work.
eg 2.11 == 2.11 rather than 2.15151523 == 2.15151524
This question might help you doing so.
My observation is that you are using floating point values for financial transactions. This is not a good idea. The representation of floating point numbers can be approximate for certain floating point values. It would be much better to use (long) integers to represent the pence/cents, and then represent the larger denomination in the output function.
That way your test will work.
In some contexts you may want to compare floats then use a very small constant floating point value perhaps called epsilon and have the test.
if (fabs(amount - grandtotal) < epsilon)
{
cout<<"\t\tThank You, Have a nice day! \n";
cout<<"\t \tPlease come again \n";
}

Using C++, get f(n+1)=3/4*f(n)+4 result [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 8 years ago.
Improve this question
I'm really fresh to C++, and I faced difficulties with the next question :
Write a program that asks the user to enter a number : n
THEN calculate f(n).
Notice that :
f(0)=3 and f(n+1) = 3/4 * f(n) + 4 ?
For example :
f(1)= 6.25
f(2)= 8.69
f(3)= 10.52
f(4)= 11.89
f(5)= 12.92
====================================================
So, how can I solve this?
thanks for all..
I try this code depending on Mr. paxdiablo answer :
#include<iostream>
using namespace std;
int main()
{
double x=0.0;
cout<<" enter an integer N:";
cin>> x;
double f1(double x)
{
if x==0.0
return 3;
return 3 / 4 * f1 (x-1) + 4;
}
return 0;
}
But the program never runs!
================================================
The Correct Solution is :
#include<iostream>
#include<iomanip> //To enable "setprecision" tool
using namespace std;
double f(int x){
if (x==0)
{return 3;}
return (3.0/4.0) * f(x-1) + 4.0; //we add zeros to get "double" results
}
int main()
{
int n=0;
cout<<" Please, enter an integer :";
cin>> n;
cout<<fixed<<setprecision(2)<<f(n); //"setprecision" used to get only two digits after the point
return 0;
}
BIG thanks to everyone gave me a hand and special thank to Mr. paxdiablo.
This sounds like a job for ... Recursion Man!
Simply define a recursive function that returns 3 when n is zero or calls itself with a reduced problem.
Pseudo-code would be something like
def f(x):
if x == 0:
return 3
return 3 / 4 * f(n-1) + 4
You can use std::cin >> dv to get a value from the user and that function (recoded in C++) to do the grunt work. Then std::cout << result to output the result. Just remember to use doubles rather than ints, including constants like 3.0.
You have to define the recursive function f, then read the input from the user, then apply the function to the input you've read (probably as an integer?), and print the output.

Using a counter-controlled while loop [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
The program should be print the numbers 0 through 10, along with their values doubled and tripled. The data file contains the necessary variable declarations and output statements.
Example the output:
single 1 double 2 triple 3
single 2 double 4 triple 6
single 3 double 6 triple 9
single 4 double 8 triple 12
here my code tell me if correct
#include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
int x, double, triple;
int x = 0
while (x<=10)
{
cout << "x" << double = (x*2) << triple = (x*3) << endl;
x++;
}
return EXIT_SUCCESS
I'll attempt to put a guiding answer so I'm not going to give you a straight code that you can just copy and paste into your homework, but if you read and follow it, it should be the answer. (And next time, do go find your lecturer, or your tutor).
Some issues:
You are not printing the "Single" and "double" and "Triple" text which you should (based on your expected answer) So add that in.
You did your calculation to get the number for double, and triple - good. But again, you did not print them out.
Also C++ allows you to stack multiple cout all on one line, so for example:
cout << "My name is " << myname << endl;
Will print out:
My name is (content of variable myname)
And then print an end of line (endl). You can use that same technique to do part of your assignment to print out the results to meet the expected output.
Credit to Synetech
you miss a lot of code in there. You didn't print nothing what you want
try again with this inside while loop:
cout << “single “ << x << double << x*x
<<“ triple “<< x*x*x << endl;
x++;

Translation of number into strings [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
I would like to know whether there is a way in which we can print the number alphabetically i.e
123 should be printed as one two three.
The only condition is that we should not reverse the number and we should not use array.
I only know these two ways:
"Reverse the number", that is, taking the last digit and cutting it off. For each cut-off digit, one can use an array to look up the correct string.
using switch and a lot of cases
Any ideas?
for hundreds place:
int hundreds = my_num / 100 //Needs "/", NOT "%"
if(hundreds == 0)
cout << "zero";
else if(hundreds == 1)
cout << "one";
//repeat for 2-9
This process could be tweaked to do the other digits as well. It is also worth mentioning that the if/else block a) could be done with a switch/case if preferred, and b) could pretty easily be made into a separate function to avoid having to repeat the block of code over and over, I just wrote out as much as I did for clarity's sake. Note that this assumes the number you're "translating" is an integer. With integers the "/" operator will return the full quotient WITHOUT the remainder, e.g. 123 / 100 = 1, not 1.23
Not necessarily the easiest route, but you can make a function, say DigitToWord which will take a digit 0, 1, 2, ...etc to its word with a switch statement. Then I recommend using a for loop over the number, continuously dividing by 10 and taking the mod for the loop:
int num; //my number i want to print
int div = pow(10, (int)log10(num)); //find the largest power of 10 smaller than num
while(num > 0) {
int remainder = num%div;
int digit = num/div;
DigitToWord();
num = remainder;
}