Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

How to implement the collatz sequence in C++

1 Answer

0 votes
#include <iostream>
 
/*
 
- The sequence begins with a positive integer: n
- If n is odd, the next number is: 3n+1
- If n is even, the next number is: n/2
- The sequence ends with: 1
 
*/
 
 
void collatz_sequence(int n) {
    std::cout << n << " ";
    while (n > 1) {
        if (n % 2 == 0) { // even
            n = n / 2;
        }
        else { // odd
            n = 3 * n + 1;
        }
        std::cout << n << " ";
    }
}
 
 
int main(void)
{
    collatz_sequence(7);
}
 
 
 
 
/*
run:
 
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 
 
*/
 

 



answered Jul 26, 2022 by avibootz
edited Jul 26, 2022 by avibootz

Related questions

1 answer 83 views
83 views asked Jul 26, 2022 by avibootz
1 answer 106 views
1 answer 124 views
1 answer 100 views
1 answer 135 views
1 answer 134 views
1 answer 111 views
...