my solution for (3n+1) is exceeding 3 sec time limit - c++

here i have written a program on (3n+1) problem.it's also a problem from UVa. I believe it's a known problem.but when i am going to submit it in that online judge community it is sending me a Time Exceeding Error. the time limit is 3 sec. I have done what my little knowledge can do. If anyone can help me with some more advice I would be glad. my code is:
#include <iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
int loop=1;
unsigned short *cyclelength;
while(loop=1){
unsigned int x,y,i,j,num,count=0,p,k,c,max;
for(;;){
cout<<"enter two integers. they must not be equal and must be between 1 and 1000000\n";
while(!(cin>>i>>j)){
cout<<"please enter a number\n";
cin.clear();
cin.ignore(1000,'\n');
}
if(i>=1 && i<1000000 && j>=1 && j<1000000 && i!=j){
break;
}
else{
printf("try the whole process again\n");
}
}
if(i>j){
x=i;
y=j;
}
else{
x=j;
y=i;
}/*making x always greater than y*/
cyclelength=(unsigned short *)malloc(1000000 *sizeof(unsigned short));
if (NULL==cyclelength){
printf("process aborted");
return 0;
}
else{
/*solution part for the range of number. and solution for each number put into cyclelength.*/
num=y;
while(num<=x){
p=1;
k=num;
while(k!=1){
if(k%2==0)
k=k/2;
else
k=3*k+1;
p+=1;
}
cyclelength[count]=p;
num+=1;
count+=1;
}
c=0;
max=cyclelength[c];
for(c=0;c<x-y-1;c+=1){
if(max<cyclelength[c+1]){
max=cyclelength[c+1];
}
}
free(cyclelength);
cyclelength = NULL;
cout<<i<<" "<<j<<" "<<max<<'\n';
}
}
}

The problem is that you are not allowing your program to end when online judging engine has finished providing inputs. You need to detect that the judging engine has finished providing inputs and then exit the program.
There is a sample code (in C) on their website here Spoiler Alert: This is actually a solution to 3n+1 problem that kind of explains this. Notice the following condition in Main.
while (scanf("%d %d\n",&m,&n)==2){//perform logic}
This will keep the program running only while there are inputs to be processed.

If your program is running successfully on your pc, but is giving time limit exceeding problem while you are submitting in any online judge community. It is sure that your algorithm is not most efficient. Online line judge communities put the time limit for any program such that an upper average programmer only can design their algorithm. Try to make your programming algorithm best after that try to take it to any online judge community. If you are using any test like >= or <= in your program it takes too much time to run your program.

Related

why my recursion code to print no in increasing order not working for input greater than 10^5?

here is my code -
#include<bits/stdc++.h>
#define ll long long
using namespace std;
void printno(ll n){
if(n==1){
cout<<1<<endl;
return;
}
printno(n-1);
cout<<n<<"\t";
}
int main(){
ll n;
cin>>n;
printno(n);
return 0;
}
i am using vs code. and my code not working for input greater than 10^5. what is the problem in my code? and how can i get output for input greater than 10^7.
You probably ran out of stack space on your platform by trying to have more than 100,000 recursive calls on the stack at once. The website we are on is named after the thing that happened to your program. I'm not sure what your end goal is here, but try to come up with a way to do it without recursion or without recursing so many times (e.g. use a simple for loop).

Program getting stuck

I have written a program for Round Robin Scheduling for CPU processes. The program was working fine before, but all of a sudden, the program stops working after several lines of code. I have tried to restart the Dev C++ app but the issue still persists. Is something wrong with my code?
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int i,n,time,remaining,temp,quantum_time;
int wt=0,atat=0; //wt = Waiting Time, atat = Average Turn Around Time
cout<<"Enter the number of processes to be scheduled"<<endl;
cin>>n;
remaining=n;
vector<int>at(n);
vector<int>bt(n);
vector<int>rt(n); //Dynamic array declaration using 'vector' library
cout<<"Enter the Arrival Time and Burst Time for all the processes"<<endl;
for(i=0;i<n;i++)
{
cin>>at[i];
cin>>bt[i];
rt[i]=bt[i];
}
cout<<"Enter the Quantum Time:"<<endl;
cin>>quantum_time;
cout<<"\n\nProcess\t\t: Arrival Time\t: Burst Time\t: Turnaround Time : Waiting Time\n\n";
for(time=0,i=0;remaining!=0;)
{
if(rt[i]<=quantum_time&&rt[i]>0)
{
time+=rt[i];
rt[i]=0;
temp=1;
}
else if(rt[i]>0)
{
rt[i]-=quantum_time;
time+=quantum_time;
}
if(rt[i]==0&&temp==1)
{
remaining--;
printf("Process{%d}\t:\t%d\t:\t%d\t:\t %d\t :\t %d\n",i+1,at[i],bt[i],time-at[i],time-at[i]-bt[i]);
cout<<endl;
wt += time-at[i]-bt[i];
atat += time-at[i];
temp=0;
}
if(i==n-1)
i=0;
else if(at[i+1]<=time)
i++;
else
i=0;
}
cout<<"Average Waiting Time: "<<wt*1.0/n<<endl;
cout<<"Average TurnAround Time: "<<atat*1.0/n<<endl;
return 0;
}
When I try to schedule 2 or more processes, the program gets stuck after displaying process 1
You have the wrong logic in the for iteration loop. The point is that your program iterates through this loop endlessly. After the first two loops, your entered data does not satisfy any condition, and i always resets to zero, so the program is constantly checking for the same unsuitable data.
The changes I've made will fix the program's freeze. But I'm not sure that I was able to keep your logic correct. So, I changed the 'for' loop like this: for (time = 0, i = 0; remaining > 0;), now we will be sure that the program will be able to complete.
Also, at the very end of the 'for' loop I put a remaining--; (approximately, line 55). I know that one of the conditions decreases this variable, but your program does not go into this condition every time.

How do I make the console print things one at a time in C++ the way Java and Python do?

I'm trying to get a feel for C++ by creating a program to efficiently find highly composite numbers, but I'm facing an inconvenience. The console waits and then prints everything at once. I want it to print things one at a time like Java and Python do. How do I do that?
Here's the code:
#include <iostream>
int main(){
int record=0; //Highest number of factors found in a number so far
for(int n=1; n<2147483647; n++){
int factors=1;
for(int PPF=2; PPF<=n; PPF++){ //PPF="Possible Prime Factor"
bool isPrime=true;
for(int i=2; i<PPF; i++){ //
if(PPF%i==0){ //Determining if the PPF is prime
isPrime=false; //
break;
}
}
if(isPrime){
if(n%PPF==0){ //Here is where I calculate the number of factors n has based on its prime factorization.
int PRP=1; //PRP="Prime Raised to Power"
int pow;
for(pow=1; n%(PRP*PPF)==0; pow++){ //Finding the exponent of a specific prime factor
PRP*=PPF;
}
factors*=pow;
}else{
break;
}
}
}
if(factors>record){
record=factors;
std::cout<<n; //Print the highly composite number
printf("\n"); //Gotta make a new line the old-fashioned way cuz this is a low-level language
}
}
}
I'm running this on VS Code with CodeRunner and all the necessary C/C++ extensions.
More precisely, you need std::flush. std::endl prints a line break and flushes, but flush does so without the break. You can also print to std::cerr which is not buffered and prints everything directly.

Did I miss a code or something?

so I'm trying to write a guess the number game in C++.The computer is Supposed to take a random number with 4 digits then the player should enter a number too.Rules are:
if the computer chooses:1234
And the player enters:1356
1 must be displayed in green,3 must in yellow since it's in the wrong place and 5&6 in red.the game goes on till the player gets the right answer.
#include<iostream>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#include<unistd.h>
using namespace std;
int main()
{
int b;
HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
cout<<"System is now generating a number...."<<"\n";
int *Number = new int[4];
srand (time(NULL));
for(int counter=0;counter<4;)
{
Number[counter]=(rand()%9)+1;
if(Number[counter]!=Number[counter-1]&Number[counter]!=Number[counter-2]
2]&Number[counter]!=Number[counter-3])
{
counter ++;
}
else
{
counter--;
}
}
cout<<Number[0]<<Number[1]<<Number[2]<<Number[3]<<"\n";
int *Guess=new int[4];
cout<<"please enter 4 digits for your number"<<"\n";
for(int counterG=0;counterG<4;counterG++) //line 34
{
cin>>Guess[counterG];
for(int counter;counter<4&counter>0;)
{
if((counter=counterG)&(Guess[counterG]=Number[counter])) //line 40
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,10);
cout<<b<<"\n";
}
if((counter=counterG)&(Guess[counterG]==Number[counter- 1]|Guess[counterG]==Number[counter+1]|Guess[counterG]==Number[counter-2]|Guess[counterG]==Number[counter+2]))
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,14);
cout<<b<<"\n";
}
else
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,12);
cout<<b<<"\n";
}
}
}
now the program is fine until line 34 but nothing happens after that!
It just gets the player digits
I'd be glad if you could tell me what I've done wrong
Not a complete answer, but it's too long for a comment:
if(Number[counter]!=Number[counter-1]&Number[counter]!=Number[counter-2]
2]&Number[counter]!=Number[counter-3])
This line alone contains a lot of errors:
To have the logical AND operator you need &&, not &.
You have typed an extra 2] at the beginning of the second line. I hope it's just a typo that you introduced when writing the question.
The first time you run this, counter is 0. What happens when you try to access Number[counter-3]? It's an out of bounds access, which leads to Undefined Behaviour, which can lead to anything.
And there are probably many more.
What to do now:
Work on your code indentation. It's really bad.
Start from a much simpler program, and verify that it works. Then, add one small step, verify it, and don't move on until you are happy with the result
Turn on your compiler warnings. Warnings are your friends, not a boring annoyance
Learn how to use a debugger. You won't go very far without debugging.
1- replace & with &&(AND operator)
2- take input in a simple integer variable and then validate the number by performing first check of number greater than 0 and less than 9999.
3- then seperate digits from this variable and then assign those digits to aaray indexes respectvely.

How to set a priority for the execution of the program in source code?

I wrote the following code, that must do search of all possible combinations of two digits in a string whose length is specified:
#include <iostream>
#include <Windows.h>
int main ()
{
using namespace std;
cout<<"Enter length of array"<<endl;
int size;
cin>>size;
int * ps=new int [size];
for (int i=0; i<size; i++)
ps[i]=3;
int k=4;
SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
while (k>=0)
{
for (int bi=0; bi<size; bi++)
std::cout<<ps[bi];
std::cout<<std::endl;
int i=size-1;
if (ps[i]==3)
{
ps[i]=4;
continue;
}
if (ps[i]==4)
{
while (ps[i]==4)
{
ps[i]=3;
--i;
}
ps[i]=4;
if (i<k)
k--;
}
}
}
When programm was executing on Windows 7, I saw that load of CPU is only 10-15%, in order to make my code worked faster, i decided to change priority of my programm to High. But when i did it there was no increase in work and load of CPU stayed the same. Why CPU load doesn't change? Incorrect statement SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);? Or this code cannot work faster?
If your CPU is not working at it's full capacity it means that your application is not capable of using it because of causes like I/O, sleeps, memory or other device throughtput capabilties.
Most probably, however, it means that your CPU has 2+ cores and your application is single-threaded. In this case you have to go through the process of paralellizing your application, which is often neither simple nor fast.
In case of the code you posted, the most time consuming operation is actually (most probably) printing the results. Remove the cout code and see for yourself how fast the code will work.
Increasing the priority of your programm won't help much.
What you need to do is to remove the cout from your calculations. Store your computations and output them afterwards.
As others have noted it might also be that you use a multi-core machine. Anyway removing any output from your computation loop is always a first step to use 100% of your machines computation power for that and not waste cycles on output.
std::vector<int> results;
results.reserve(1000); // this should ideally match the number of results you expect
while (k>=0)
{
for (int bi=0; bi<size; bi++){
results.push_back(ps[bi]);
}
int i=size-1;
if (ps[i]==3)
{
ps[i]=4;
continue;
}
if (ps[i]==4)
{
while (ps[i]==4)
{
ps[i]=3;
--i;
}
ps[i]=4;
if (i<k)
k--;
}
}
// now here yuo can output your data
for(auto&& res : results){
cout << res << "\n"; // \n to not force flush
}
cout << endl; // now force flush
What's probably happening is you're on a multi-core/multi-thread machine and you're running on only one thread, the rest of the CPU power is just sitting idle. So you'll want to multi-thread your code. Look at boost thread.