My function has to be able to print the sum of the numbers 1+1+1.... to get to N. I can only enter N. For example: sumaRecursiva(6): 1+1+1+1+1+1=6.
This is what I have:
int sumaRecursiva(int y) {
int x=0;
if (x == y){
return y;
}
else {
x += 1;
cout << x << "+" <<endl;
sumaRecursiva(y-1);
}
}
You may want another function to handle the fact that you need fewer + characters in your print than you need 1s
void printSum(int y) {
if (y == 0) return;
cout << 1;
printPlusRecursive(y - 1);
}
void printPlusRecursive(int y) {
if (y == 0) return;
cout << '+' << 1;
printPlusRecursive(y - 1);
}
or shorter, but more complex version:
void printSum(int y, bool firstCall = true) {
if (y == 0) return;
if (firstCall) cout << 1;
else cout << '+' << 1;
printSum(y - 1, false);
}
If you want the output to be exactly 1+1+1+1+1+1=6 then you will need a helper function sumaRecursivaHelper to print the 1+'s and the outer function to print the =n which I believe none of the other answers include.
#include <iostream>
using namespace std;
void sumaRecursivaHelper(int x) {
if (x == 0) {
cout << 1;
}
else {
cout << "1+";
sumaRecursivaHelper(x - 1);
}
}
void sumaRecursiva(int x) {
if (x == 0) {
cout << 0;
}
else {
sumaRecursivaHelper(x);
}
cout << "=" << x;
}
int main()
{
sumaRecursiva(6);
return 0;
}
Your recursive function should return a value.
The value passed to a recursive is usually used to test for the escape condition (not usually used as part of the result).
int sum(int N)
{
if (N == 0) {
return 0; // I like zero as the escape value.
// Though this will give you
// sum(6) = 1 + 1 + 1 + 1 + 1 + 1 + 0 = 6
// If you only want to add ones change
// the escape condition to 1 and return 1
// Though this will prevent you doing sum(0)
}
return 1 + sum(N-1);
}
Related
I want to print an X shape using n number of rows but without any loop. I have to use a recursive function to print the X.
I have called the functions along with space function but it didn't print the X. It printed:
* *
* *
* *
I have to solve this problem using recursion. No for loop or while loop is allowed to solve this one.
// C++ implementation to print the given
// pattern recursively
#include <bits/stdc++.h>
using namespace std;
// function to print the 'n-th' row of the
// pattern recursively
int g;
void printPatternRowRecur(int n) {
if (n < 1)
return;
if (n = 1) {
cout << "*";
}
// print the remnaining stars of the n-th row
// recursively
else {
return;
}
printPatternRowRecur(n - 1);
}
void print_space(int space) {
// base case
if (space == 0)
return;
cout << " ";
// recursively calling print_space()
print_space(space - 1);
}
int s;
void Rhombus(int n) {
// base condition
if (s >= n)
return;
else {
print_space(s);
printPatternRowRecur(n);
print_space(n - s);
printPatternRowRecur(n);
}
// print the stars of the n-th row
s++;
// move to next line
cout << endl;
// print stars of the remaining rows recursively
Rhombus(n);
}
// Driver program to test above
int main() {
int n = 3;
//cout << "Enter the number of lines you want to print" << endl;
//cin >> n;
//cout << endl << "Rhombus" << endl;
Rhombus(n);
return 0;
}
if (n = 1) should be if (n == 1). As coded, the if expression is always true.
Here is a simplified version:
// C++ implementation to print the given pattern recursively
#include <iostream>
using namespace std;
void print_spaces(int n) {
if (n > 0) {
cout << ' ';
print_spaces(n - 1);
}
}
void rhombus(int s, int n) {
if (s < n) {
int left = min(s, n - s - 1);
int middle = n - 2 * left - 2;
print_spaces(left);
cout << '*';
if (middle >= 0) {
print_spaces(middle);
cout << '*';
}
cout << endl;
// print stars of the remaining rows recursively
rhombus(s + 1, n);
}
}
void rhombi(int s, int n) {
if (s <= n) {
cout << endl << "Rhombus " << s << endl;
rhombus(0, s);
rhombi(s + 1, n);
}
}
int main() {
//int n = 3;
//cout << "Enter the number of lines you want to print" << endl;
//cin >> n;
//cout << endl << "Rhombus" << endl;
//rhombus(0, n);
rhombi(0, 7);
return 0;
}
#include <iostream>
using namespace std;
// * *
// * *
// *
// * *
// * *
//printStarHorizontally will recursively print '*' on a line using x coordinates
void printStarHorizontally(int xCoordinate1, int xCoordinate2, int currentXCoordinate, int maxCoordinate){
if(currentXCoordinate >= maxCoordinate) {
cout<<endl;
return;
}
if(currentXCoordinate == xCoordinate1 || currentXCoordinate == xCoordinate2) {
cout<<"*";
} else {
cout<<" ";
}
printStarHorizontally(xCoordinate1, xCoordinate2, currentXCoordinate + 1, maxCoordinate);
}
//PrintCross will go to each height and then use printStarHorizontally func. to print star on that particular height
void PrintCross(int heightOfCross, int currentHeight) {
if(currentHeight >= heightOfCross) return;
printStarHorizontally(currentHeight, heightOfCross-currentHeight-1, 0, heightOfCross);
PrintCross(heightOfCross,currentHeight+1);
}
int main() {
// heightOfCross should be odd integer
int heightOfCross = 13;
PrintCross(heightOfCross, 0);
return 0;
}
Here's a recursion with one function, one given parameter, and two default parameters:
#include <iostream>
using namespace std;
void f(int y, int x=1, int w=0){
if (y < 1)
return;
if (x > 0){
f(y, -(y + 2 * w), w);
f(y - 2, x, w + 1);
if (y > 1)
f(y, -(y + 2 * w), w);
return;
}
if (x == -w){
cout << endl;
return;
}
if (x == -(w + y) || x == -(w + 1))
cout << '*';
else
cout << ' ';
f(y, x + 1, w);
}
int main(){
f(5);
cout << endl;
f(6);
return 0;
}
I would use two recursive functions: first to write a character after a number of spaces, second to write the lines.
#include <iostream>
/*************************************
* display on character (c) on out after x spaces recursively
* **********************************/
void display_char(int x, std::ostream& out = std::cout, char c='*') {
if (x == 0) out << c;
else {
out << ' ';
display_char(x-1, out, c);
}
}
/*********************************
* displays lines to draw an X pattern
* The pattern is composed of c characters on out
* x decreases to 0 while y increases and a c
* is printed at positions x and y
* ******************************/
void display_line(int x, int y=0, std::ostream& out=std::cout, char c='*') {
int oldx=x, oldy=y;
if (x < y) {
int t = x;
x = y;
y = t;
}
display_char(y, out, c);
if (x != y) display_char(x - y, out, c);
out << '\n';
if (oldx > 0) display_line(oldx-1, oldy+1, out, c);
}
int main() {
int x;
std::cout << "X size (int): ";
std::cin >> x;
display_line(x-1);
return 0;
}
Keep in mind I've only been using CPP for around a week so the code is not very good. I wrote this to solve the problem 1362A on CodeForces. Long story short, the code works fine except for the fact that it says the memory used is 262100 KB. I've looked over it multiple times but can't find anything that would cause lots of memory to be used.
#include <iostream>
#include <cstdint>
using namespace std;
uint64_t makeq(uint64_t x, uint64_t y)
{
uint64_t q;
if (x >= y)
{
q = x / y;
}
else
{
q = y / x;
}
return q;
}
bool check(uint64_t x, uint64_t y, uint64_t q)
{
if (x >= y)
{
if (x % y != 0)
{
cout << -1 << "\n";
return false;
}
}
else
{
if (y % x != 0)
{
cout << -1 << "\n";
return false;
}
}
//checking float
if (q > 8 && q % 8 != 0)
{
cout << -1 << "\n";
return false;
}
if (q == 1)
{
cout << 0 << "\n";
return false;
}
if (q % 2 != 0)
{
cout << -1 << "\n";
return false;
}
return true;
}
int main()
{
uint64_t n, x, y, q, c;
cin >> n;
while (n--)
{
c = 0;
cin >> x >> y;
q = makeq(x, y);
if (check(x, y, q) == false)
{
continue;
}
while (q > 1)
{
if (q >= 8 && q % 8 == 0)
{
q /= 8;
c += 1;
}
else
{
if (q >= 4 && q % 4 == 0)
{
q /= 4;
c += 1;
}
else
{
q /= 2;
c += 1;
}
}
}
cout << c << endl
<< flush;
}
return 0;
}
**
The following code takes input x and y and then calls a function. The function is supposed to be called 3 times in which case it will return 1. If, however, the values of x or y decline to very low levels the function won't be called 3 times in which case it will return 0.
My input is 3, 22. I can see that the value of t becomes 3 after the function has been called 3 times, but, it returns the value 0 instead of 1 (as seen from the value of i). Can someone explain why this is happening?
PS : Some sections of the code have been removed so that we can focus only on the relevant parts.
#include <iostream>
using namespace std;
int turn_yeh(int &x, int &y)
{
static int t = 0;
cout << "t : " << t << " x: "<< x<< " y : " << y<<endl;
if (t != 0 && t% 3 == 0) return 1;
if(x!= 0 && t!= 2){x--; t++; turn_yeh(x,y);}
else if(y >=10 && t!=2){y -= 10*t; turn_yeh(x,y);}
if( y >= 2 && t == 2){y -= 2; t++; turn_yeh(x,y);}
else return 0;
}
int main()
{
int x, y;
cin >> x >> y;
int i = 1;
while (1)
{
i = turn_yeh(x ,y);
cout << "i : " << i << endl;
if (i == 0)
{
cout << "Hanako";
return 0;
}
}
}
If you had written out your braces using one of the established conventions, you would have quickly discovered that there is not an explicit return value on all program control paths.
That means the behaviour of your code is undefined. (Note that main is an exception to this rule, with implicit return 0; statements added implicitly.)
You probably mean to write return turn_yeh(x, y) on the missing branches.
Reference: https://en.wikipedia.org/wiki/Indentation_style
Your function probably needs to return the result of the recursive call:
int turn_yeh(int &x, int &y)
{
static int t = 0;
cout << "t : " << t << " x: "<< x<< " y : " << y<<endl;
if (t != 0 && t% 3 == 0) return 1;
if(x!= 0 && t!= 2){x--; t++; return turn_yeh(x,y);}
else if(y >=10 && t!=2){y -= 10*t; return turn_yeh(x,y);}
if( y >= 2 && t == 2){y -= 2; t++; return turn_yeh(x,y);}
else return 0;
}
Non-Recursive Code
Here is the code I am trying to convert into a recursive solution.
int main()
{
int number[3];
for (number[0]=0; number[0] <= 9; number[0]++)
{
for (number[1]=0; number[1] <= 4; number[1]++)
{
for (number[2]=0; number[2] <= 9; number[2]++)
{
std::cout << number[0] << number[1] << number[2] << std::endl;
}
}
}
std::cout << "Press any key to continue";
std::cin.ignore();
return 0;
}
The output of this code can be found here http://pastebin.com/f20X3gT3.
Recursive Attempt
Here is my failed attempt at replicating the above algorithm into a recursive solution. It compiles without any errors but it does not give the same results as the above Non-Recursive solution does.
#include <iostream>
const int NumberLength = 3;
int number[3];
int element;
void generateFormula(const int Length) {
if(Length == 0) {
for (int n = 0; n <= NumberLength; ++n) {
std::cout << number[n];
}
std::cout << std::endl;
return;
}
if(element%2==0) {
for(number[element]=0; number[element] <= 9; number[element]++);
generateFormula(Length-1);
}
else {
for(number[element]=0; number[element] <= 4; number[element]++);
generateFormula(Length-1);
}
element++;
}
int main()
{
for (int i = 0; i <= NumberLength; ++i)
generateFormula(i);
std::cout << "Press any key to continue";
std::cin.ignore();
return 0;
}
Output:
0000
10000
10501
10500
If you change your function a little bit, you'll be able to see how it can be transformed to a recursive function.
// Drive it using externally supplied data.
void generateFormula1(int number[], int loopCounter[])
{
for (; number[0] <= loopCounter[0]; number[0]++)
{
for (; number[1] <= loopCounter[1]; number[1]++)
{
for (; number[2] <= loopCounter[2]; number[2]++)
{
std::cout << number[0] << number[1] << number[2] << std::endl;
}
}
}
}
Now, it is a bit easier to transform it to a recursive function.
void generateFormula2(int number[], int loopCounter[], int nestingLevel)
{
// The terminating condition of the recursive function.
if ( nestingLevel == 3 )
{
std::cout << number[0] << number[1] << number[2] << std::endl;
return;
}
for (; number[nestingLevel] <= loopCounter[nestingLevel]; number[nestingLevel]++)
{
generateFormula2(number, loopCounter, nestingLevel+1);
}
}
Test it using:
int main()
{
int loopCounter[3] = {9, 4, 9};
int number1[3] = {0};
generateFormula1(number1, loopCounter);
int number2[3] = {0};
generateFormula2(number2, loopCounter, 0);
return 0;
}
See it working at http://ideone.com/JH76sa.
You can simplify your function quite a bit. Using std::setw() and std::setfill() you don't need to have three different variables.You can change the iterative approach to
void print()
{
for (int i = 0; i < 950; i++)
{
cout << setw(3) << setfill('0') << i << "\n";
if (((i+1) % 50) == 0)
i += 50;
}
}
Live Example
And the recursive approach would become:
void print(int i)
{
cout << setw(3) << setfill('0') << i << "\n";
if (i == 949)
return;
if (((i+1) % 50) == 0)
i += 50;
print(++i);
}
Live Example
void print(int x, int y, int z){
std::cout << '(' << x << ", " << y << ", " << z << ")\n";
++x;
if(x == 10){
x = 0;
++y;
if(y == 10){
y = 0;
++z;
if(z == 10)
return;
}
}
print(x, y, z);
}
auto main() -> int{
print(0, 0, 0);
}
This will print out (0, 0, 0) through to (9, 9, 9)
You can replace x, y and z with whatever you like and modify the parameters of the if statements to get the results you want. You could also generalize the function to get a limit for each parameter:
template<int XLim, int YLim, int ZLim>
void print(int x, int y, int z){
std::cout << '(' << x << ", " << y << ", " << z << ")\n";
if(z >= ZLim && y >= YLim && z >= ZLim) return;
++x;
if(x == 10){
x = 0;
++y;
if(y == 10){
y = 0;
++z;
if(z == 10) return;
}
}
print<XLim, YLim, ZLim>(x, y, z);
}
auto main() -> int{
print<9, 4, 9>(0, 0, 0);
}
I'm trying to write program to calculate and display the number of primes in the first 50 “chiliads”. There must be 2 user defined functions "isPrime" and "primeCount". It seems like the "primeCount" is appending 4469969 to every count. It isn't doing that when I paste it into the main function.
int main (){
long x = 1;
long y = 1000;
char reply;
cout << "Start End Number of Primes" << endl;
while (y <= 50000)
{
cout << x << " " << y << " ";
cout << primeCount(x, y) << endl;
x = 1000 + x;
y = 1000 + y;
}
//exits the program
cout << "Enter q to quit... ";
cin >> reply;
return 0;
}// End main function
bool isPrime(long n)
{
long i = 2;
if (n == 1)
return false;
if (n == 2)
return true;
if (n == 3)
return true;
if ((n % 2) == 0)
return false;
if ((n % 3) == 0)
return false;
while (i < n)
{
if (n % i == 0 )
{
return false;
}
else
{
i++;
}
}
return true;
}
long primeCount (long x, long y)
{
long count = 0;
while (x < y)
{
if (isPrime(x) == 1)
{
count++;
}
x++;
}
cout << count;
}
You were not returning a value from "primeCount" you were printing it.
I cleaned up the code as follows, along with some optimizations (we prove that the candidate is odd, so we don't need to check even divisors, and we only check for the value of 2 when we already know the number is even, saving us 1 extra test per odd number).
#include <iostream>
// prototypes for functions we implement after we use them.
long primeCount(long x, long y);
bool isPrime(long n);
int main (){
long x = 1;
long y = 1000;
std::cout << "Start End Number of Primes" << std::endl;
while (y <= 50000)
{
std::cout << x << " " << y << " ";
std::cout << primeCount(x, y) << std::endl;
x += 1000;
y += 1000;
}
return 0;
}
bool isPrime(long n)
{
if((n & 1) == 0) // even
return (n == 2);
if(n == 1)
return false;
for (long i = 3; i < n / 2; i += 2)
{
if ((n % i) == 0 )
return false;
}
return true;
}
long primeCount(long x, long y)
{
long count = 0;
while (x < y)
{
if (isPrime(x))
count++;
++x;
}
return count;
}