For 2 numbers x and n entered by the user, my code needs to find Hn(x) defined recursively by the following formulas:
I am trying to implement a recursive version and and iterative version of that function. But I think I am getting the wrong concept of it, since my code doesn't compile due to errors on H(n) and H[n]:
#include "pch.h"
#include <iostream>
int H(int n, int x) //function for recursion
{
if (n < 0) return -1;
else if (n == 0) return 1;
else if (n == 1) return 2 * x;
return 2 * x * H(n) * x - 2 * n * H(n - 1) * x;
}
int H1(int n, int x) //function for Iterator
{
int *H1 = new int[n + 1];
H[0] * x = 1;
H[1] * x = 2 * x;
for (int i = 0; i <= n; i++)
{
H[i] * x = 2 * x * H[n] * x - 2 * n * H[n - 1] * x;
}
return H1(n) * x;
}
int main()
{
int n, x;
std::cout << "Enter the number n: ";
std::cin >> n;
std::cout << "Enter the number x: ";
std::cin >> x;
std::cout << "Rec = " << H[n] * x std::endl;
std::cout << "Iter = " << H1[n] * x std::endl;
}
It is confusing, I apologize for that as I am completely new to functions.
I already managed to do this with fibonacci sequence. And there I used only one parameter for function f(x) that is f(int n){... }, but here I am a bit confused with two parameters in function H(int n, int x) , where n is the index of H while x is an integer.
Yes, you need to translate your matematically indexed function into a function with 2 parameters.
The recursive version is almost ok, except for some shifts in the indexes:
int H(int n, int x) // recursive version
{
if (n <= 0)
return -1;
else if (n == 1)
return 1;
else if (n == 2)
return 2 * x;
else
return 2 * x * H(n-1, x) - 2 * n * H(n - 2, x); // shift n+1, n n-1 to n, n-1 n-2
}
Your iterative version needs rework, since you should write it as a loop, if possible without cashing the values that you no longer need. For example:
int Hi(int n, int x) //iterative version
{
if (n <= 0)
return -1;
else if (n == 1)
return 1;
int am2 = 1; // start for for n-2
int am1 = 2*x; // start for n-1
if (n == 2)
return am1;
int am;
for (int i=3; i<=n; i++) {
am = 2*x*am1 - 2*i*am2; // calculate Hn from Hn-1 and Hn-2
//prepare next interation
am2=am1;
am1=am;
}
return am;
}
Online demo
You wrote:
int H(int n, int x) //function for recursion
{
if (n < 0) return -1;
else if (n == 0) return 1;
else if (n == 1) return 2 * x;
return 2 * x * H(n) * x - 2 * n * H(n - 1) * x;
}
You're not far from a working program. Drop that H1 function. Let's see:
int H(int n, int x)
{
switch(n)
{
// H_0(x) = 1
case 0: return 1;
// H_1(x) = 2x
case 1: return 2 * x;
// H_{n+1}(x) = 2x H_n(x) - 2n H_{n - 1}(x)
default:
return 2*x*H(n-1, x) - 2*(n-1)*H(n-2, x);
}
}
The trick part is realizing than the n in H_{n+1}(x) = 2x H_n(x) - 2n H_{n - 1}(x) and in return 2*x*H(n-1, x) - 2*(n-1)*H(n-2, x);are not the same, they differ by one.
Now, you only need to handle user I/O and calling your H function with user input.
Related
I need to convert this recursive function into tail recursive function but i am getting the wrong output can any help me out with this.
Here is the function definition:
f(n) = 3f(n − 1) - f(n − 2) + n,
with initial conditions f(0) = 1 and f(1) = 2.
#include <iostream>
using namespace std;
int headRecursion(int n) {
if(n == 0) {
return 1;
}
if (n == 1) {
return 2;
}
return 3 * headRecursion(n - 1) - headRecursion(n - 2) + n;
}
int main(){
cout << endl << headRecursion(3);
return 0;
}
This is kind of an interesting problem. We can start with how to implement as a loop:
int minus2 = 1;
int minus1 = 2;
if (n == 0) return minus2;
if (n == 1) return minus1;
for( int i = 2; i <= n; i++)
{
int next = minus1 * 3 - minus2 + i;
minus2 = minus1;
minus1 = next;
}
return minus1;
The takeaway is we need to count UP. In order to make this tail recursive we need to pass in our accumulators (there is no reason to do this other than to show off, but it adds nothing to readability or efficiency)
int tailRecursive(int minus2, int minus1, int step, int n)
{
if (step == n) return minus1;
return tailRecursive(minus1, minus1*3 - minus2 + step+1, step+1, n);
}
you can use an intermediate to set it up and handle the n==0 case.
int calcIt(int n) {
if (n == 0) return 1;
// step must start with 1, since we handled 0 above
return tailRecursive(1, 2, 1, n);
}
Something along these lines:
std::pair<int, int> next_result(std::pair<int, int> prev_result, int n) {
return {3*prev_result.first - prev_result.second + n, prev_result.first};
}
std::pair<int, int> tailRecursion(int n) {
if (n == 0) {
return {1, 0};
}
if (n == 1) {
return {2, 1};
}
return next_result(tailRecursion(n-1), n);
}
int compute(int n) {
return tailRecursion(n).first;
}
int main(){
std::cout << compute(3) << std::endl;
}
Demo
The key is that you need a function that computes a pair {f(n), f(n-1)} given the previously computed pair {f(n-1), f(n-2)}
Strong number is the number that the sum of the factorial of its digits is equal to number itself.
For example: 145, since
1! + 4! + 5! = 1 + 24 + 120 = 145
Here is my code, It passes most of the test except one test
#include <string>
using namespace std;
string strong_num (int number )
{
int sum = 0;
while(number != 0) {
int last = number % 10;
number /= 10;
sum+= last * (last-1);
}
if(sum == number)
return "STRONG!!!!";
else
return "Not Strong !!";
}
What is wrong with my code?
I'm surprised you're passing any test cases at all. For one thing, you are destroying number before you compare it to sum, and for another your logic is flawed.
Try this:
int factorial (int x)
{
int result = 1;
while (x > 1)
{
result *= x;
x--;
}
return result;
}
string strong_num (int number)
{
int sum = 0;
int x = number;
while (x != 0) {
int digit = x % 10;
sum += factorial (digit);
x /= 10;
}
if (sum == number)
return "STRONG!!!!";
else
return "Not Strong !!";
}
Live demo
Replace int by long long to be able to test larger numbers.
There are two problems:
first - you are changing the value of number before comparing it to sum,
second - the thing you used last * (last-1) is not a definition of factorial, the definition of factorial is factorial(x) = 1 * 2 * 3 * ... * x
int factorial (int x) {
if(x < 2) return 1;
return x * factorial(x - 1);
}
string strong_num (int number)
{
int sum = 0;
int x = number;
while (x != 0) {
int last = x % 10;
sum += factorial (last);
x /= 10;
}
if (sum == number)
return "STRONG!!!!";
else
return "Not Strong !!";
}
Question:
Write C++ function to evaluate the following formula for a given x:
The following code was designed in C++ on Visual Studio to be a solution of the above mentioned problem. However whenever I run the code what I am returned is the value of x; or the same value I input.
I don't understand what the problem may be, so I would appreciate any help given.
#include <iostream>
using namespace std;
unsigned long fact(int n) {
if (n <= 1) {
return 1;
}
else {
return n * fact(n - 1);
}
}
unsigned long f(int x, int n) {
static unsigned long term;
static unsigned long sum = 0;
do {
term = pow(x, (2 * n + 1)) / fact((2 * n) + 1);
n++;
sum += term;
} while (term < 0.000001);
return sum;
}
int main() {
int y = 0;
int x;
cout << "enter x" << endl;
cin >> x;
cout << f(x, y) << endl;
system("pause");
}
I suggest you don't calculate powers and factorials on each iteration. Each next term can be generated by multiplying the previous one by x^2 / [n(n+1)]:
double sinh_in_disguise(const double x) {
const double x_sq = x * x;
double term = x;
double sum = 0;
double n = 2;
while (true) {
const double new_sum = sum + term;
if (new_sum == sum)
break;
sum = new_sum;
term *= x_sq / (n * (n + 1));
n += 2;
}
return sum;
}
int main() {
std::cout.precision(16);
double x = 2.019;
std::cout << sinh_in_disguise(x) << std::endl; // prints 3.699001094869803
std::cout << std::sinh(x) << std::endl; // prints 3.699001094869803
}
put double datatype in the whole code and it will work perfectly
I am trying to implement my own square root function which gives square root's integral part only e.g. square root of 3 = 1.
I saw the method here and tried to implement the method
int mySqrt(int x)
{
int n = x;
x = pow(2, ceil(log(n) / log(2)) / 2);
int y=0;
while (y < x)
{
y = (x + n / x) / 2;
x = y;
}
return x;
}
The above method fails for input 8. Also, I don't get why it should work.
Also, I tried the method here
int mySqrt(int x)
{
if (x == 0) return 0;
int x0 = pow(2, (log(x) / log(2))/2) ;
int y = x0;
int diff = 10;
while (diff>0)
{
x0 = (x0 + x / x0) / 2; diff = y - x0;
y = x0;
if (diff<0) diff = diff * (-1);
}
return x0;
}
In this second way, for input 3 the loop continues ... indefinitely (x0 toggles between 1 and 2).
I am aware that both are essentially versions of Netwon's method but I can't figure out why they fail in certain cases and how could I make them work for all cases. I guess i have the correct logic in implementation. I debugged my code but still I can't find a way to make it work.
This one works for me:
uintmax_t zsqrt(uintmax_t x)
{
if(x==0) return 0;
uintmax_t yn = x; // The 'next' estimate
uintmax_t y = 0; // The result
uintmax_t yp; // The previous estimate
do{
yp = y;
y = yn;
yn = (y + x/y) >> 1; // Newton step
}while(yn ^ yp); // (yn != yp) shortcut for dumb compilers
return y;
}
returns floor(sqrt(x))
Instead of testing for 0 with a single estimate, test with 2 estimates.
When I was writing this, I noticed the result estimate would sometimes oscillate. This is because, if the exact result is a fraction, the algorithm could only jump between the two nearest values. So, terminating when the next estimate is the same as the previous will prevent an infinite loop.
Try this
int n,i;//n is the input number
i=0;
while(i<=n)
{
if((i*i)==n)
{
cout<<"The number has exact root : "<<i<<endl;
}
else if((i*i)>n)
{
cout<<"The integer part is "<<(i-1)<<endl;
}
i++;
}
Hope this helps.
You can try there C sqrt implementations :
// return the number that was multiplied by itself to reach N.
unsigned square_root_1(const unsigned num) {
unsigned a, b, c, d;
for (b = a = num, c = 1; a >>= 1; ++c);
for (c = 1 << (c & -2); c; c >>= 2) {
d = a + c;
a >>= 1;
if (b >= d)
b -= d, a += c;
}
return a;
}
// return the number that was multiplied by itself to reach N.
unsigned square_root_2(unsigned n){
unsigned a = n > 0, b;
if (n > 3)
for (a = n >> 1, b = (a + n / a) >> 1; b < a; a = b, b = (a + n / a) >> 1);
return a ;
}
Example of usage :
#include <assert.h>
int main(void){
unsigned num, res ;
num = 1847902954, res = square_root_1(num), assert(res == 42987);
num = 2, res = square_root_2(num), assert(res == 1);
num = 0, res = square_root_2(num), assert(res == 0);
}
Source
How to create all possible numbers, starting from a given one, where all digits of the new ones are moved one slot to the right? For example if we have 1234. I want to generate 4123, 3412 and 2341.
What I have come out with so far is this:
int move_digits(int a)
{
int aux = 0;
aux = a % 10;
for(int i=pow(10, (number_digits(a) - 1)); i>0; i=i/10)
aux = aux * 10 + ((a % i) / (i/10));
return aux;
}
But it doesn't work.
The subprogram number_digits looks like this (it just counts how many digits the given number has):
int number_digits(int a)
{
int ct = 0;
while(a != 0)
{
a = a/10;
ct++;
}
return ct;
}
I think there is no need to write separate function number_digits.
I would write function move_digits simpler
#include <iostream>
#include <cmath>
int move_digits( int x )
{
int y = x;
double n = 0.0;
while ( y /= 10 ) ++n;
return ( x / 10 + x % 10 * std::pow( 10.0, n ) );
}
int main()
{
int x = 1234;
std::cout << x << std::endl;
std::cout << move_digits( x ) << std::endl;
}
Retrieving the last digit of n: n % 10.
To "cut off" the last digit, you could use number / 10.
Say you have a three-digit number n, then you can prepend a new digit d using 1000 * d + n
That said, you probably want to compute
aux = pow(10, number_digits - 1) * (aux % 10) + (aux / 10)
Calculatea/(number_digits(a) - 1) and a%(number_digits(a) - 1)
And your answer is (a%(number_digits(a) - 1))*10 + a/(number_digits(a) - 1)
int i =0 ;
int len = number_digits(a);
while(i < len){
cout << (a%(len - 1))*10 + a/(len - 1) <<endl;
a = (a%(len - 1))*10 + a/(len - 1);
}
void move_digits(int a)
{
int digits = 0;
int b = a;
while(b / 10 ){
digits++;
b = b / 10;
}
for (int i = 0; i < digits; ++i)
{
int c = a / 10;
int d = a % 10;
int res = c + pow(10, digits) * d;
printf("%d\n", res);
a = res;
}
printf("\n");
}
int main()
{
move_digits(12345);
}