I'm trying to write a function for the first n terms of sqrt(1+sqrt(2+sqrt(3+...))) in C++. The constraint is that the function must be recursive and take n (the depth of the nest) as the only parameter. I do not need to return the expression itself, just what it evaluates to. For example:
n=1 -> sqrt(1) # which evaluates to 1
n=2 -> sqrt(1+sqrt(2)) # which evaluates to 1.55377
n=3 -> sqrt(1+sqrt(2+sqrt(3))) # which evaluates to 1.7122
I've tried:
float nestedRadical(float n){
if (n==1){
return sqrt(1);
}else{
return sqrt(n + nestedRadical(n-1));
}
}
This code causes 1 to be the most deeply nested radical, when it should be the highest. How should should I approach this problem?
Examine and analyze nested radicals carefully. Write on paper, even if needed. then you will understand better.
Try this:
#include <iostream>
#include <math.h>
using namespace std;
double recursivelNestedRadicals(int n, int i) {
double res = 0;
if(i-1 == n)
return res;
else
res = sqrt(i + recursivelNestedRadicals(n, i+1));
}
int main() {
int number;
cout<<"Enter number: ";
cin>>number;
cout<<recursivelNestedRadicals(number, 1);
}
Related
#include<iostream>
#include<cmath>
using namespace std;
float san= 0.25 ; float var= 0.75;
int findFact(int n)//factorial
{
return n == 1 ? 1 : n * findFact(n - 1);
}
int findNcR(int n, int r)//combination nCr
{
return findFact(n) / (findFact(n - r) * findFact(r));
}
double prob(int s, int v){ //recursive function for probability
if(s>=5) return 1; if(v>=5) return 0;
double sum = 0;
int m = 5-s;
for( int i=0; i<=m; i++){
sum += prob(s+i,v+m-i)*findNcR(m,i)*pow(san,i)*pow(var,m-i);
}
return sum;
}
int main(){
cout<< prob(2,1);
}
In DEV C++, there is no output printed when I compile and run the above code. I think its because of large fractional values involved. Any idea how I can get the output?
Please check the logic you use in your double prob(int s, int v) method.
You are going to infinity recursive like
S=2 V=1
S=2 V=4
S=2 V=7
The base case for your recursion, s==5 or v==5 is never getting hit. As you call your function with s=2, every time the prob function is called it is setting m to 3, and so on the first iteration of the loop (when i==0) it calls prob with s=2 and v=v+3. As you start with v==1, it successively calls prob(2,1), prob(2,4), prob(2,7), etc... and never gets any further.
I don't know what probability distribution you are trying to code so I can't offer any specific advice on how to fix this.
The question asks me to find the greatest power devisor of (number, d) I found that the function will be like that:
number % d^x ==0
I've done so far using for loop:
int gratestDevisor(int num, int d){
int p = 0;
for(int i=0; i<=num; i++){
//num % d^i ==0
if( (num % (int)pow(d,i))==0 )
p=i;
}
return p;
}
I've tried so much converting my code to recursion, I can't imagine how to do it and I'm totally confused with recursion. could you give me a tip please, I'm not asking you to solve it for me, just some tip on how to convert it to recursion would be fine.
Here is a simple method with recursion. If ddivides num, you simply have to add 1 to the count, and divide num by d.
#include <stdio.h>
int greatestDevisor(int num, int d){
if (num%d) return 0;
return 1 + greatestDevisor (num/d, d);
}
int main() {
int num = 48;
int d = 2;
int ans = greatestDevisor (num, d);
printf ("%d\n", ans);
return 0;
}
A recursive function consist of one (or more) base case(es) and one (or more) calls to the function itself. The key insight is that each recursive call reduces the problem to something smaller till the base case(es) are reached. State (like partial solutions) are either carried in arguments and return value.
You asked for a hint so I am explicitly not providing a solution. Others have.
Recursive version (which sucks):
int powerDividing(int x, int y)
{
if (x % y) return 0;
return 1 + powerDividing(x/y, y);
}
the point of this exercise is to multiply a digit of a number with its current position and then add it with the others. Example: 1234 = 1x4 + 2x3 + 3x2 + 4x1 .I did this code successfully using 2 parameters and now i'm trying to do it with 1. My idea was to use - return num + mult(a/10) * (a%10) and get the answer, , because from return num + mult(a/10) i get the values 1,2,3,4- (1 is for mult(1), 2 for mult(12), etc.) for num, but i noticed that this is only correct for mult(1) and then the recursion gets wrong values for mult(12), mult(123), mult(1234). My idea is to independently multiply the values from 'num' with a%10 . Sorry if i can't explain myself that well, but i'm still really new to programming.
#include <iostream>
using namespace std;
int mult(int a){
int num = 1;
if (a==0){
return 1;
}
return ((num + mult(a/10)) * (a%10));
}
int main()
{
int a = 1234;
cout << mult(a);
return 0;
}
I find this easier and more logically to do, Hope this helps lad.
int k=1;
int a=1234;
int sum=0;
while(a>0){
sum=sum+k*(a%10);
a=a/10;
k++;
}
If the goal is to do it with recursion and only one argument, you may achieve it with two functions. This is not optimal in terms of number of operations performed, though. Also, it's more of a math exercise than a programming one:
#include <iostream>
using namespace std;
int mult1(int a) {
if(a == 0) return 0;
return a % 10 + mult1(a / 10);
}
int mult(int a) {
if(a == 0) return 0;
return mult1(a) + mult(a / 10);
}
int main() {
int a = 1234;
cout << mult(a) << '\n';
return 0;
}
Program number 1:
In a given range a and b where a<=b, I want to find whether a number is a perfect quare, if yes then print its root. Therefore, I wrote the following code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
float squaredroot(int n) {
float low = 0.0, mid;
float high = (float)n+1;
while ((high-low) > 0.00001) {
mid = (low+high) / 2;
if (mid*mid < n) {
low = mid;
}
else {
high = mid;
}
}
return low;
}
int main() {
int a,b,i=0; cin>>a>>b;
float roo=0.0;
for(i=a;i<=b;i++){
roo=squaredroot(i);
if(floor(roo)==roo){
cout<<roo<<endl;
}
}
return 0;
}
For the given input 1 5 the output should be 2. But, the above program is not printing any value.
Nevertheless, when I tried running another program using the same base concept as Program number 1, that's mentioned above, It was executed perfectly.
The task for the following program is to check whether the input is a perfect square or not. If yes, then print the root of the number, else print "Not a perfect square!". Here is the code for the Program number 2:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
float squaredroot(int n) {
float low = 0.0, mid;
float high = (float)n+1;
while ((high-low) > 0.00001) {
mid = (low+high) / 2;
if (mid*mid < n) {
low = mid;
}
else {
high = mid;
}
}
return low;
}
int main() {
int a; cin>>a;
float roo=0.0;
roo=squaredroot(a);
if(floor(roo)==roo){
cout<<roo<<endl;
}
else{
cout<<"Not a perfect square!"<<endl;
}
return 0;
}
I am unable to find the mistake in the first program. Please help.
Instead of messing about with the square root function, consider this:
Consecutive squares are separated by succeeding odd numbers.
It's pretty darned fast to add some integers. Also you are skipping more and more numbers each time.
Square root takes you to floats. This keeps the problem in integers, where it belongs.
So, to solve your problem elegantly, just do this:
#include <iostream>
using std::cout;
void print_perfect_square( int start, int end ) {
int x = 0, nthOdd = 1;
while ( x <= end ) {
if ( x >= start ) {
cout << x << " is a square and its root is "
<< nthOdd - 1 << '\n';
}
x += 2*nthOdd - 1;
++nthOdd;
}
}
int main() {
// it should find 9 and 16
print_perfect_square(6,17);
cout << '\n';
// it sholuld skip negatives
print_perfect_square(-10,5);
cout << '\n';
// it should print 25,36...
print_perfect_square(20,100);
return 0;
}
As Gyro Gearloose said, the problem is that squaredroot(4) returns 1.99999809, so floor(roo)!=roo. One way to fix this is to change the condition (floor(roo)==roo) to (fabs(roo - floor(roo+0.5)) < 0.00001). Notice that I'm using the same 0.00001 from the function squaredroot.
I'm writing a recursion function to find the power of a number and it seems to be compiling but doesn't output anything.
#include <iostream>
using namespace std;
int stepem(int n, int k);
int main()
{
int x, y;
cin >> x >> y;
cout << stepem(x, y) << endl;
return 0;
}
int stepem(int n, int k)
{
if (n == 0)
return 1;
else if (n == 1)
return 1;
else
return n * stepem(n, k-1);
}
I tried debugging it, and it says the problem is on this line :
return n * stepem(n, k-1);
k seems to be getting some weird values, but I can't figure out why?
You should be checking the exponent k, not the number itself which never changes.
int rPow(int n, int k) {
if (k <= 0) return 1;
return n * rPow(n, --k);
}
Your k is getting weird values because you will keep computing until you run out of memory basically, you will create many stack frames with k going to "-infinity" (hypothetically).
That said, it is theoretically possible for the compiler to give you a warning that it will never terminate - in this particular scenario. However, it is naturally impossible to solve this in general (look up the Halting problem).
Your algorithm is wrong:
int stepem(int n, int k)
{
if (k == 0) // should be k, not n!
return 1;
else if (k == 1) // this condition is wrong
return 1;
else
return n * stepem(n, k-1);
}
If you call it with stepem(2, 3) (for example), you'll get 2 * 2 * 1 instead of 2 * 2 * 2 * 1. You don't need the else-if condition:
int stepem(int n, unsigned int k) // unless you want to deal with floating point numbers, make your power unsigned
{
if (k == 0)
return 1;
return n * stepem(n, k-1);
}
Didn't test it but I guess it should give you what you want and it is tail recursive.
int stepemi(int result, int i int k) {
if (k == 0 && result == i)
return 1;
else if (k == 0)
return result;
else
return stepem(result * i, i, k-1);
}
int stepem(int n, int k) {
return stepemi(n, n, k);
}
The big difference between this piece of code and the other example is that my version could get optimized for tail recursive calls. It means that when you call stepemi recursively, it doesn't have to keep anything in memory. As you can see, it could replace the variable in the current stack frame without having to create a new one. No variable as to remain in memory to compute the next recursion.
If you can have optimized tail recursive calls, it also means that the function will used a fixed amount of memory. It will never need more than 3 ints.
On the other hand, the code you wrote at first creates a tree of stackframe waiting to return. Each recursion will add up to the next one.
Well, just to post an answer according to my comment (seems I missed adding a comment and not a response :-D). I think, mainly, you have two errors: you're checking n instead of k and you're returning 1 when power is 1, instead of returning n. I think that stepem function should look like:
Edit: Updated to support negative exponents by #ZacHowland suggestion
float stepem(int n, int k)
{
if (k == 0)
return 1;
else
return (k<0) ?((float) 1/n) * stepem(n, k+1) :n * stepem(n, k-1);
}
// Power.cpp : Defines the entry point for the console application.
//
#include <stream>
using namespace std;
int power(int n, int k);
void main()
{
int x,y;
cin >>x>>y;
cout<<power(x,y)<<endl;
}
int power(int n, int k)
{
if (k==0)
return 1;
else if(k==1) // This condition is working :) //
return n;
else
return n*power(n,k-1);
}
your Program is wrong and it Does not support negative value given by user,
check this one
int power(int n, int k){
'if(k==0)
return 1;
else if(k<0)
return ((x*power(x,y+1))*(-1));
else
return n*power(n,k-1);
}
sorry i changed your variable names
but i hope you will understand;
#include <iostream>
using namespace std;
double power(double , int);// it should be double because you also need to handle negative powers which may cause fractions
int main()
{
cout<<"please enter the number to be powered up\n";
double number;
cin>>number;
cout<<"please enter the number to be powered up\n";
int pow;
cin>>pow;
double result = power(number, pow);
cout<<"answer is "<<result <<endl;
}
double power( double x, int n)
{
if (n==0)
return 1;
if (n>=1)
/*this will work OK even when n==1 no need to put additional condition as n==1
according to calculation it will show x as previous condition will force it to be x;
try to make pseudo code on your note book you will understand what i really mean*/
if (n<0)
return x*power(x, n-1);
return 1/x*power(x, n+1);// this will handle negative power as you should know how negative powers are handled in maths
}
int stepem(int n, int k)
{
if (k == 0) //not n cause you have to vary y i.e k if you want to find x^y
return 1;
else if (k == 1)
return n; //x^1=x,so when k=1 it should be x i.e n
else
return n * stepem(n, k-1);
}