Recursion

Hi I am writing a program that prompts the user to write a positive integer N and then computes S(N) = the sum from k=1 to N of H(k) and reports this values.

For every number n, H(n) denotes the number of time required to get an output of 1 by repeatedly applying the function f(n).

f(n) is defined as:

if n is even: n/2
if n is odd: 3n+1

To get a value of 1, I must apply f as many times as necessary, for example H(7) = 16.

This is more complicated than anything I have done before and I am trying to read up on recursion. I know the attached code is wrong. I am wondering if I have to call a function and how to incorporate returning a value for H(k).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
#include<string>
#include<cmath>

using namespace std;

int main(){
    int N;
    cout << "Please enter a positive integer: ";
    cin >> N;
    
    if(N==1){
        return 1;
    }
    else(N!=1);{
        if(N%2 == 0){
            N = N/2;
        }
        else{
            N = (3*N)+1;
        }
    }

}
  
I am wondering if I have to call a function

Yes, you have to call a function. Recursion means that function must also call itself.

Line 15: What is this? You can't have a condition on an else. Also, the ; terminates the else.

Topic archived. No new replies allowed.