Coin Change C++ - 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;

Related

Unable to find the error in the code I wrote for a question on loops in C++. Could anyone point it out?

a beginner at coding here.
I was practising loops(c++) when I stumbled upon this problem:-
Write a program in C++ to find the perfect numbers between 1 and 500. (6,28 and 496)
Perfect number: It is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3.
I wrote the following code:-
#include <iostream>
using namespace std;
int main() {
int n=2; //test numbers from 2 to 500.
int div=1; //divisor for n.
int sum=0; //sum of divisors which divide n.
while (n<=500) {
while (div<n){ //if div divides n, then it will added to sum and incremented, else only incremented.
if (n%div==0){
sum=sum+div;
div++;
} else{
div++;
}
}
if (sum==n){
cout<<n<<" is a perfect number."<<endl;
n++;
} else{
n++;
}
}
return 0;
}
The code is supposed to print that 6, 28 and 496 are perfect numbers.
But instead, it's not printing anything. Haven't been able to find the error yet after checking for 30+ minutes.
Could anyone point out the error?
You forget to re-initialize some variables in your loop.
for seems more appropriate than while here.
Create sub function also help to "identify" scope.
#include <iostream>
bool isPerfectNumber(int n)
{
int sum = 0;
for (int div = 1; div != n; ++div) {
if (n % div == 0) {
sum += div;
}
}
return sum == n && n > 0;
}
int main()
{
for (int i = 2; i != 501; ++i) {
if (isPerfectNumber(i)) {
std::cout << n << " is a perfect number." << std::endl;
}
}
return 0;
}
#include<iostream>
using namespace std;
bool perfect_num(int x);
int main() {
int m, n, x;
cout << "input the range m, n: " << "\n";
cin >> m >> n;
for (x = m; x <= n; ++x) {
if (perfect_num(x)) {
cout << x << " ";
}
}
return 0;
}
bool perfect_num(int x) {
bool flag = false;
//initialize
int sum = 0, i;
//loop 1 to x
for (i = 1; i < x; ++i) {
//judge whether is the factor
if (x % i == 0) {
sum += i;
}
}
//update flag
flag = (sum == x);
return flag;
}
#include<iostream>
using namespace std;
//judge function
bool isPerfectNum(int num){
int tmp = 0;
for (int i = 1; i < num; ++i) {
if (num % i == 0) {
tmp += i;
}
}
return tmp == num;
}
int main(){
cout << "Perfect Number contains: ";
for (int i = 1; i <= 500; ++i){
if (isPerfectNum(i)) {
cout << i << " ";
}
}
cout << "\n";
return 0;
}
at the end of your first loop, you should bring back div and sum to their default value.
int main() {
int n=2; //test numbers from 2 to 500.
int div=1; //divisor for n.
int sum=0; //sum of divisors which divide n.
while (n<=500) {
while (div<n){ //if div divides n, then it will added to sum and incremented, else only incremented.
if (n%div==0){
sum=sum+div;
div++;
} else{
div++;
}
}
if (sum==n){
cout<<n<<" is a perfect number."<<endl;
n++;
} else{
n++;
}
div = 1; // you should bring them back here.
sum = 0;
}
return 0;
}

C++) how to distinct 1.0E+1000 number's aliquot?

If input A < 10^1000 , b = common int <100000
how can Ii know that A is multiple of B or not?
int main()
{
int testcase = 0;
cin >> testcase;
for (int i = 0; i < testcase; i++)
{
long long num;
int div = 0;
cin >> num >> div;
if (num % div == 0)
{
cout << 1 << endl;
}
else
{
cout << 0 << endl;
}
}
return 0;
}
this is what i tried.
The first step is to read (or set) the large number as a string.
The second step consists in convert this string to a vector of int, each int being less than 10000.
The last step is to calculate a modulo b, in the same way we are performing a division by hand
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
std::vector<int> conver_to_vect_int (const std::string &a) {
std::vector<int> x;
int n = a.size();
x.reserve (n/5 + 1);
for (int i = 0; i < n; i += 5) {
int max = std::min (i+5, n);
std::string s (a.begin() + i, a.begin() + max);
int number = std::stoi (s);
x.push_back (number);
}
return x;
}
int modulo (const std::string &a_string, int b) {
std::vector<int> a = conver_to_vect_int (a_string);
int mod = 0;
for (int val: a) {
int val_with_mod = mod * 100000 + val;
mod = val_with_mod % b;
}
return mod;
}
int main() {
std::vector<std::string> list_s = {"29", "111111111", "111111111111111111111111111111111111", "111111111111111211111111111111111111"};
int b = 9;
for (auto &s: list_s) {
int mod = modulo (s, b);
bool divisibility = mod == 0;
std::cout << "divisibility of " << s << " by " << b << " = " << divisibility << "\n";
}
}

C++ : Recursion (Variables losing value)

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.

Program to print first 5 perfect numbers, is printing 2096128?? C++

So this program will print perfect numbers, but one of them, 2096128, is being printed for some reason? Would really appreciate some help figuring out what is happening! Thank you! I can't figure out why one non perfect number is finding it way into the sequence!
#include <iostream>
#include <string>
#include <math.h>
#include <iomanip>
bool isPerfect(int n);
using namespace std;
int main() {
long long perfect = 0;
int first = 0;
first = (pow(2, 2 - 1))*(pow(2, 2) - 1);
cout << first << endl;
for (int i = 3, j = 1; j < 5; i += 2) {
if (isPerfect(i)) {
perfect = (pow(2, i - 1)*(pow(2, i) - 1));
cout << perfect << endl;
j++;
}
}
// pause and exit
getchar();
getchar();
return 0;
}
bool isPerfect(int n)
{
if (n < 2) {
return false;
}
else if (n == 2) {
return true;
}
else if (n % 2 == 0) {
return false;
}
else {
bool prime = true;
for (int i = 3; i < n; i += 2) {
if (n%i == 0) {
prime = false;
break;
}
}
return prime;
}
}
You're pretty much complicating this task.
Here's what I came up with:
#include <iostream>
using namespace std;
bool isPerfect(long long n);
int main()
{
int count = 5;
long long sum = 1;
for (int i = 3; count >= 0; i += 2)
{
sum += i * i * i;
if (isPerfect(sum))
{
cout << sum << endl;
count--;
}
}
system("pause");
return 0;
}
bool isPerfect(long long n)
{
int sum = 0;
for (int i = 1; i < n; i++)
{
if (n % i == 0)
sum += i;
}
return sum == n;
}
It sure isn't perfect, but will do for 5 numbers. Consider that it'll be very slow for more than 5 numbers.

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.