234k views
5 votes
6. (18) Create a function (prob3_6) that will do the following: Input a positive scalar integer x. If x is odd, multiply it by 3 and add 1. If the given x is even, divide it by 2. Repeat this rule on the new value until you get 1, if ever. Your program will output how many operations it had to perform to get to 1 and the largest number along the way.

User RockBoro
by
5.7k points

1 Answer

5 votes

Answer:

The programming language is not stated, so I'll make use of C++ programming language

Comments are used for explanatory purpose

Program starts here

#include<iostream>

using namespace std;

void prob_36(int n) //Declare Function

{

//Declare and Initialize nummber of operation to 0

int num = 0;

//Declare and initialize largest

int largest = 0;

while(n!=1)//Iterate until number is 0

{

if(n % 2 == 0)//Check for even

{

n/=2;

}

else // Check for odd

{

n*=3;

n++;

}

cout<<n<<'\t'; //Print result

if(largest<n) // Test for largest

{

largest = n;

}

num++; //Increment number of operation

}

cout<<endl;

//Print number of operations

cout<<"Number of operation: "<<num<<endl;

//Print largest number along the way

cout<<"Largest number along the way: "<<largest;

}

int main()

{

int n;

//Prompt user for input

cout<<"Enter any positive integer number: ";

cin>>n;

if(n<1)

{

cout<<"Number must be greeater than 0";

}

else

{

prob_36(n); //Call Function

}

return 0;

}

User Mike Monkiewicz
by
6.2k points