Need to count a sum of arithmetic progression using recursion c++ - c++

I need to sum the members of my progression using recursion. Here's the function which gives my progression and how to count a sum in recursion way?
#include <iostream>
using namespace std;
void progressionRec(int a1, int d, int n) {
if(n <= 1){
cout << a1 << " ";
} else {
int next = a1 + d;
progressionRec(next, d, n - 1);
cout << a1 << " ";
}
}
int main()
{
progressionRec(2,3,15);
return 0;
}

You can sum the members of your progression this way
#include <iostream>
int progressionSum(int a, int d, int n) {
if (n > 0) {
return a + progressionSum(a + d, d, n - 1);
}
return 0;
}
int main()
{
std::cout << "Sum: " << progressionSum(2, 3, 15) << std::endl;
return 0;
}

You may use a functor to store the progress count. Here's an example implementation:
#include <iostream>
using namespace std;
class progressionRec
{
public:
void operator()(int a1, int d, int n) {
++count;
if(n <= 1){
cout << a1 << " ";
} else {
int next = a1 + d;
operator()(next, d, n - 1);
cout << a1 << " ";
}
}
size_t getCount() const
{
return count;
}
private:
std::size_t count = 0;
};
int main()
{
auto func = progressionRec();
func(2,3,15);
std::cout << "\nCount:" << func.getCount() << std::endl;
return 0;
}
Output:
44 41 38 35 32 29 26 23 20 17 14 11 8 5 2
Count:15

You need to change returning type of function to int and return sum on each return:return a1 + progressionRec(next, d, n - 1);

Related

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.

Decompose a number in its prime factors

I have this recursive function that decompose a number in its prime factors, and show the result standard output for example
descompon(2, 10);
Output
2 = 2
3 = 3
4 = 2^2
5 = 5
6 = 2 * 3
7 = 7
8 = 2^3
9 = 3^2
10 = 2 * 5
The code
#include <iostream>
#include <sstream>
int comprobar_primo( int* num, int e )
{
if (*num%e == 0)
{
*num /= e;
return 1 + comprobar_primo(num, e);
}
return 0;
}
std::string factor_primo(int a, int b, std::stringstream& fact)
{
unsigned exp = comprobar_primo(&a, b);
if (exp >= 1)
{
fact << b;
if (exp > 1) fact << '^' << exp;
if (a != 1) fact << " * ";
}
if (a > 1) factor_primo(a, b + 1, fact);
return fact.str();
}
void descompon(int a, int b, int ver)
{
std::stringstream fact;
//std::string result = factor_primo(a, 2, fact);
if(ver)
std::cout << a << " = " << factor_primo(a, 2, fact) << std::endl;
if(a < b)
descompon( a + 1, b, ver);
}
int main(void)
{
descompon(2, 10000, 1);
return 0;
}
The problem is that when reaches the 5922 the program remains frozen, showing:
Process returned -1073741819 <0xC0000005>
why this happens and how I can avoid?
Both your factor_primo and descompon functions can potentially cause stack overflow. Its better to convert them into iterative version. Modified code is given below:
// no need to pass b as argument since we start from b=2 and increment b by 1
std::string factor_primo(int a, std::stringstream& fact)
{
for(int b=2; a>1; b++)
{
if(a%b==0)
{
unsigned exp=comprobar_primo(&a, b);
if(exp >= 1)
{
fact << b;
if(exp > 1) fact << '^' << exp;
if(a != 1) fact << " * ";
}
}
}
return fact.str();
}
void descompon(int a, int b, int ver)
{
if(ver)
{
for(int i=a; i<=b; i++) {
std::stringstream fact;
std::cout << i << " = " << factor_primo(i, fact) << std::endl;
}
}
}
int main(void)
{
descompon(2, 10000, 1);
getchar();
return 0;
}

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.

C++, code to write the binary form of an integer after the decimal point

What I want is to take in an integer, and convert it to binary in a method as close to the method shown in the below code. However, I want to convert the number to binary as if it were after a decimal point. So if I got 625 as input then I would want it converted into 101.
Given the code:
#include <iostream>
using namespace std;
int decTobinary(int);
int main(){
cout << "Enter a number = ";
int num;
cin >> num;
int answer = decTobinary(num);
cout << "answer: " << answer << endl"
return 0;
}
int decTobinary(int x) {
if (x==0)
return 0;
return 10 * decTobinary(x/2) + x % 2;
}
I hacked it together so it's not pretty but it gives the output you were looking for:
#include <iostream>
float intToDecimalPoint(float f)
{
if((f / 10.0f) <= 1.0f)
return f/10.0f;
else
return intToDecimalPoint(f/10.0f);
}
void decTobinary(int x)
{
if (x==0)
return;
float decimalPoint = intToDecimalPoint(float(x));
if(decimalPoint*2.0f >= 1.0f)
{
std::cout << 1;
int newX = int((decimalPoint*2.0f - 1.0f)*(float(x)/decimalPoint));
return decTobinary(newX);
}
else
{
std::cout << 0;
decTobinary(x*2);
}
}
int main()
{
std::cout << "Enter a number = ";
int num;
std::cin >> num;
std::cout << "answer: ";
decTobinary(num);
std::cout << std::endl;
std::cin.get();
std::cin.get();
return 0;
}
Algo is from here. My solution is not perfect due to floating point imprecision but it should work for most cases?
You could try
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int GetNumberOfDigits (int i)
{
return i > 0 ? (int) log10 ((double) i) + 1 : 1;
};
void function(int number, vector<int> &convert) {
double remainder = number/pow(10,GetNumberOfDigits(number));
do
{
remainder = remainder*2;
convert.push_back(int(remainder));
remainder = remainder - int(remainder);
}
while(remainder != 0);
};
int main() {
vector<int> solution;
int n;
cout<<"Enter number: ";
cin>>n;
function (n, solution);
for(int index = 0; index < solution.size(); index++) std::cout<<solution[index];
return 1;
}
Archive for the ‘C Programming’ Category
http://www.programmingclub.in/category/c-programming/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],n,i,j=0;
printf(“Enter the Number: “);
scanf(“%d”,&n);
while(n>0)
{
i=n%2;
a[j++]=i;
n=n/2;
}
j–;
printf(“\nBinary form is: \n”);
while(j>=0)
{
printf(“%d”,a[j]);
j–;
}
getch();
}