Answer:
The code example is given below with explanation in c++ language.
Explanation:
Comments will explain what's going on in the code. Below code is already compiled and tested.
#include <time.h>
#include <iostream>
#include <sstream>
using namespace std;
int main(void)
{
//defining start and end time variable
// which will be used to break the infinte loop
time_t endwait;
time_t start = time(NULL);
time_t seconds = 3; // end loop after this time has elapsed
cout<<"Input your number :";
long userNum;
cin>> userNum;
// initializing end time by adding seconds with start time
endwait = start + seconds;
// defining outputString which will concatenate all the
// divisible numbers in loop
string outputString="";
// bool isCompleted will use to check whether our
// loop breaks successfully or time is expired.
bool isCompleted=true;
// iterate loop until it comes to 1. as in loop
// the program already displayed the 1 value.
while (userNum>1)
{
// checking start and end time comparison to
// break the infinite loop after some seconds
if(start >= endwait){
cout<< "Program end never reached.";
isCompleted=false;
break;
}
userNum=userNum/2;
// defining stringstream to convert from long to string
stringstream longToString;
longToString<<userNum;
// concatenating all the values
outputString = outputString + longToString.str()+" ";
// re initializing the start time with current time.
start = time(NULL);
}
// check if while loop breaks successfully then print the
// series of numbers here.
if(isCompleted) {
cout << outputString;
}
return 0;
}