C++ : Recursion (Variables losing value) - c++

I made a simple recursion program for this question http://www.spoj.com/problems/COINS/, but whenever recursion happens my class variables lose their value and store the value from the recursion loop.
Here's the code:
#include<iostream>
using namespace std;
class a
{
public:
int c = 0, d = 0, b = 0, x = 0;
int recur(int n)
{
b = (n / 2);
if (b >= 12)
{
b = recur(b);
}
c = (n / 3);
if (c >= 12)
{
c = recur(c);
}
d = (n / 4);
if (d >= 12)
{
d = recur(d);
}
x = b + c + d;
return x;
}
};
int main()
{
int n;
while(cin)
{
cin >> n;
int b = 0, r = 0;
a abc;
r = (n > abc.recur(n)) ? (n) : (abc.recur(n));
cout << r << endl;
}
return 0;
}
So for input 12, I'll be getting 13 but for the input value of 44 I'm getting 44.

This could be a working solution:
#include <iostream>
using namespace std;
int changeToDollars(int bytelandians) {
int byTwo = bytelandians / 2;
int byThree = bytelandians / 3;
int byFour = bytelandians / 4;
int sum = byTwo + byThree + byFour;
if (sum < bytelandians) {
return bytelandians;
} else {
return changeToDollars(byTwo) + changeToDollars(byThree) + changeToDollars(byFour);
}
}
int main() {
int bytelandians;
cout << "How much bytelandians?: ";
while (cin >> bytelandians) {
cout << "Corresponding $: " << changeToDollars(bytelandians) << endl;
cout << "How much bytelandians?: ";
}
return 0;
}
The changeToDollars function, using a simple recursive algorithm, exchanges each single Byteland coin into the corresponding three ones with minor value, until the overall converted amount is advantageous.

Related

Can anyone explain what is the error I am getting in the output and how to remove it?

My code:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int BinaryToDecimal(int n)
{
int ans = 0;
int x = 1;
while (n > 0)
{
int y = n % 10;
ans = ans + x * y;
x = x * 2;
n = n / 10;
}
return ans;
}
int DecimalToBinary(int num)
{
vector<int> vect;
while (num > 0)
{
vect.push_back(num % 2);
num = num / 2;
}
int s = vect.size();
int i = s - 1;
for (i = s - 1; i >= 0; i--)
{
cout << vect.at(i);
}
return vect.at(i);
}
int main()
{
int a, b;
cout << "Enter first number: " << endl;
cin >> a;
cout << "Enter second number: " << endl;
cin >> b;
int a_deci = BinaryToDecimal(a);
int b_deci = BinaryToDecimal(b);
int sum = a_deci + b_deci;
DecimalToBinary(sum);
cout << endl;
return 0;
}
Output:
Enter first number:
10101
Enter second number:
11010
101111terminate called after throwing an instance of 'std::out_of_range'what(): vector::_M_range_check: __n (which is 18446744073709551615) >= this->size() (which is 6)
What does this error message mean and how do I fix it?
After this for loop
for (i = s - 1; i >= 0; i--)
{
cout << vect.at(i);
}
the variable i is equal to -1.
So the next call of the member function at with the value equal to -1 (that yields a very big number of the unsigned type std::vector<int>::size_type)
return vect.at(i);
throws the exception.
It seems you need to return from the function the whole vector elements of which will represent a number in the binary form.
Instead of the container std::vector<int> it will be better to use std::bitset.

Is there any better way to do this in C++? Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

This is what I came up with
#include <iostream>
using namespace std;
int serialNumber = 1;
Would recursion be better?
int factorial(int n)
{
int k=1;
for(int i=1;i<=n;++i)
{
k=k*i;
}
return k;
}
How can I go about doing this in a single for loop?
Or is this the best way?
int main()
{
int a;
int b;
int c;
int fact1;
int fact2;
int fact3;
for (a=1;a < 11;a++)
{
fact1 = factorial(a);
for (b=1;b < 11;b++)
{
fact2 = factorial(b);
for (c=1;c < 11;c++)
{
fact3 = factorial(c);
cout << serialNumber << " : ";
int LHS = fact1 + fact2 + fact3;
if (LHS == a * b * c)
{
cout << "Pass:" <<" "<< a << " & " << b << " & " << c << endl;
}
else
{
cout << "Fail" <<endl;
}
serialNumber++;
}
c = 1;
}
b = 1;
}
return 0;
}
I am being forced to add more none code into it.
Thanks for the help!
Don't know if this is helps,but>
check for minimum of A,B,C
A!+B!+C! = (min(A,B,C)!)*(1+((min+1..restfact1)!)+((min+1..restfact2)!))
So, you can calculate the minimum factorial and than re-use it for calculating others.
On the other hand, you can calculate only the maximum factorial and store its results in the array, and re-use pre-calculated values for finding factorial of smaller numbers
Other implication is that the minimum number can be reduced
restfact1 * restfact2 = ((min-1)!)*(1+((min+1..restfact1)!)+((min+1..restfact2)!))
Part of the question was how can this be done in a single loop and this is one way to do that.
I don't think this is a better way of doing it, but the question was asked:
constexpr int bound = 10;
int Factorials[bound + 1];
for (int i = 1; i <= bound; ++i) Factorials[i] = Factorial(i);
for (int i = 0; i < bound * bound * bound; ++i) {
int s = i + 1;
int a = i;
int c = 1 + a % bound;
a /= bound;
int b = 1 + a % bound;
a /= bound;
++a;
cout << s << " : ";
int LHS = Factorials[a] + Factorials[b] + Factorials[c];
if (LHS == a * b * c)
...
}

Windows C++ char not displaying properly, just some unknkown character displaying

I have written the code for RSA in C++ on Ubuntu. It was working fine on that, it's working fine on Windows Dev C++ as well, but it doesn't show the character properly.
Here is the code :
#include<iostream>
#include<stdlib.h> // for rand()
#include<math.h> // for floor function
#include<string.h>
using namespace std;
//function to check whether a number is prime or not
int check_prime(int number)
{
int count = 0;
for(int i = 2; i<number + 1; i++)
{
if(number%i == 0)
{
count++;
}
}
if(count>2)
{
return 0;
}
else
{
return 1;
}
}
//function to generate a random prime number
int generate_random_prime()
{
int temp;
while(1)
{
temp = rand() % 50;
if(check_prime(temp) == 1)
{
return temp;
}
}
}
int gcd(int a, int b)
{
int temp;
while(b != 0)
{
temp = b;
b = a%b;
a = temp;
}
return a;
}
// Extended Euclid GCD to find d such de congruent to 1
int extended_gcd(int a, int b)
{
int d, x, y, r, q;
if(b == 0)
{
d = a;
x = 1;
y = 0;
cout << "\n d= " << d << " x= " << x << " y= " << y << "\n";
}
int x2, x1, y2, y1;
x2 = 1;
x1 = 0;
y2 = 0;
y1 = 1;
while(b > 0)
{
q = floor(a / b);
r = a - q*b;
x = x2 - q*x1;
y = y2 - q*y1;
a = b;
b = r;
x2 = x1;
x1 = x;
y2 = y1;
y1 = y;
}
d = a;
x = x2;
y = y2;
return x2;
}
//returns a^b mod n using square and multiply method
int modular_exponentiation(int a, int b, int n)
{
if(a == 1)
{
return 0;
}
int c = 1;
for(int i = 1; i < b + 1; i++)
{
c = (c*a) % n;
}
return c;
}
//cipher text = (message^e) %n
int cipher_text(int m, int e, int n)
{
return modular_exponentiation(m, e, n);
}
//decrypted_text= (cipher^d)%n
int decrypt_cipher(int c, int d, int n)
{
return modular_exponentiation(c, d, n);
}
int main()
{
// generating two random prime p and q
int p = generate_random_prime();
int q = generate_random_prime();
cout << "Prime p : " << p << "and q : " << q << "\n";
int n = p*q;
cout << "n=p*q = " << n << "\n";
//calculating Euler Totient for prime p and q
int euler_phi = (p - 1)*(q - 1);
cout << "Euler totient is : " << euler_phi << "\n";
int d, e;
// calculating e such that 1<e<euler_phi and gcd(n,euler_phi)=1
while(1)
{
e = rand() % (euler_phi - 1 + 1) + 1;
if(gcd(euler_phi, e) == 1)
{
break;
}
}
cout << "e value is : " << e << "\n";
//calculating d such that ed congruent 1, ed=1
d = extended_gcd(e, euler_phi);
//d=5;
cout << "d value is : " << d << "\n";
//storing the message to be encrypted as char array and encrypting each char element
char message[20];
int cipher[20];
cout << "Enter the message to be encrypted : ";
cin >> message;
cout << "Message to be encrypted is : " << message << "\n";
int size = strlen(message);
//calculating cipher text c
for(int i = 0; i < size; i++)
{
cipher[i] = cipher_text(int(message[i]), e, n);
}
cout << "Cipher text is : ";
for(int i = 0; i < size; i++)
{
cout << cipher[i] << " ";
}
char message_decrypted[size];
//decrypting cipher text
for(int i = 0; i < size; i++)
{
message_decrypted[i] = decrypt_cipher(cipher[i], d, n);
}
cout << "\nDecrypted message is : ";
for(int i = 0; i < size; i++)
{
cout << message_decrypted[i];
}
cout << "\n";
return 0;
}
I have tried the code on DevC++ and using g++.
Check the images :
Image using g++ compiler
I need a way to print the char to be displayed properly.
I think that message_decrypted[i]=decrypt_cipher(cipher[i],d,n); needs to be changed to print the character properly in Devcpp
Here is the link to the code in online IDE where it works fine https://repl.it/#shubhamjohar/RSA
When your main routine invokes
decrypt_cipher(cipher[i], d, n);
cipher[0] is 386 as matching your output above. d is -179. And n is 697
The corresponding call into modular_exponentiation(a=386, b=-179, n=697) results in this for-loop getting skipped:
for (int i = 1; i<b + 1; i++) {
c = (c*a) % n;
}
Because i < (b + 1) evaluates to (1 < -178), which evaluates to false.
Therefore, your modular_exponentiation returns 1, which is an unprintable character.
Same applies for the subsequent calls to decrypt_cipher from main.
I don't know enough about the RSA algorithm to know if your implementation is correct. But when d is negative, that for-loop isn't going to do any loops.
Maybe it is incurred by the following expression in your program:
char message_decrypted[size];
There is some standard change related to this usage. please read the following page for more details.
https://www.geeksforgeeks.org/variable-length-arrays-in-c-and-c/
Or try to use something like new char[size] to allocate memory dynamically.

Fibonacci series

I am trying to do an exercise with the Fibonacci series.
I have to implement with a recursive function, a succession of the prime n number of Fibonacci and print them
in the same function. The problem is that my function print also the intermediate number.
The results, for example, for n = 6, should be : 1 1 2 3 5 8.
Any solutions?
Thanks
#include<iostream>
using namespace std;
int rec(int n)
{
int a, b;
if (n == 0 || n == 1)
{
return n;
}
else
{
a = rec(n - 1);
b = rec(n - 2);
cout << a + b << endl;
return a + b;
}
}
int main()
{
int n = 6;
rec(n);
return 0;
}
I have taken help of static int. That worked the way you wanted.
void rec(int n)
{
static int a=0,b=1,sum;
if(n>0)
{
sum = a+b;
a=b;
b= sum;
cout<<sum<<" ";
rec(n-1);
}
}
Though you have to print the first Fibonacci number yourself in main().
cout<<"0 ";
rec(n);
You can use this:
#include<iostream>
using namespace std;
#define MAXN 100
int visited[MAXN];
int rec(int n)
{
if(visited[n])
{
return visited[n];
}
int a, b;
if (n == 0|| n==1)
{
return n;
}
else
{
a = rec(n - 1);
b = rec(n - 2);
cout << " " <<a + b;
return visited[n] = a + b;
}
}
int main()
{
int n = 6;
cout<< "1";
rec(n);
cout<<endl;
return 0;
}
This implementation uses dynamic programming. So it reduces the computation time :)
Because you are printing in rec, its printing multiple times because of recursion. No need to print in the recursive function. Instead print the result in main
#include<iostream>
using namespace std;
int rec(int n)
{
int a, b;
if (n == 0 || n == 1)
{
return n;
}
else
{
a = rec(n - 1);
b = rec(n - 2);
//cout << a + b << endl;
return a + b;
}
}
int main()
{
int n = 6;
for (int i = 1; i <= n; i++)
{
cout << rec(i) << endl;
}
system("pause");
return 0;
}
I'm pretty sure you have gotten working solutions but I have a slightly different approach that doesn't require you to use data structures:
/* Author: Eric Gitangu
Date: 07/29/2015
This program spits out the fibionacci sequence for the range of 32-bit numbers
Assumption: all values are +ve ; thus unsigned int works here
*/
#include <iostream>
#include <math.h>
#define N pow(2.0,31.0)
using namespace std;
void fibionacci(unsigned int &fib, unsigned int &prevfib){
unsigned int temp = prevfib;
prevfib = fib;
fib += temp;
}
void main(){
int count = 0;
unsigned int fib = 0u, prev = 1u;
while(fib < N){
if( fib ==0 ){
fib = 0;
cout<<" "<< fib++ <<" \n ";
continue;
}
if( fib == 1 && count++ < 2 ){
fib = 1;
cout<< fib <<" \n ";
continue;
}
fibionacci(fib, prev);
cout<< fib <<" \n ";
}
}
Try this recursive function.
int fib(int n)
return n<=2 ? n : fib(n-1) + fib(n-2);
It is the most elegant solution I know.

Coin Change C++

I've tried to solve a coin change problem in such a way that it'll compute the minimum numbers of coins that can be used. I've used the algorithm post on http://www.algorithmist.com. Here's the algorithm:
C(N,m) = min(C(N,m - 1),C(N - Sm,m) + 1)
with the base cases:
C(N,m) = 1,N = 0
C(N,m) = 0,N < 0
C(N, m) = 0, N >= 1, m <= 0
But when I write the code it run to infinity.
Here's the code:
#include <iostream>
#include <algorithm>
using namespace std;
int Types[101];
int Coins(int N, int m)
{
if(N==0)
{
return 1;
}
else if(N<0)
{
return 0;
}
else if(N>0 && m<=0)
{
return 0;
}
else
{
int a = Coins(N,m-1);
int b = Coins(N-Types[m],m) + 1;
int c = min(a,b);
return c;
}
}
int main()
{
int noOfCoins, Target;
cin >> noOfCoins >> Target;
for(int i = 0; i<noOfCoins; i++)
{
cin >> Types[i];
}
cout << Coins(Target, noOfCoins);
return 0;
}
What can be wrong?
It should be cout << Coins(Target, noOfCoins - 1);
instead of cout << Coins(Target, noOfCoins);
Otherwise you are accessing a 0 element, and go to the same state again and again here:
int b = Coins(N-Types[m],m) + 1;