Time Limit Exceeded - Simple Program - Divisibility Test - c++

Input
The input begins with two positive integers n k (n, k<=10^7). The next n lines of input contain one positive integer ti, not greater than 10^9, each.
Output
Write a single integer to output, denoting how many integers ti are divisible by k.
Example
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4
My Code:
#include <iostream>
using namespace std;
int main()
{
long long n,k, i;
cin>>n;
cin>>k;
int count=0;
for(i=0;i<n;i++)
{
int z;
cin>>z;
if(z%k == 0) count++;
}
cout<<count;
return 0;
}
Now this code produces the correct output. However, its not being accepted by CodeChef(http://www.codechef.com/problems/INTEST) for the following reason: Time Limit Exceeded. How can this be further optimized?

As said by caleb the problem is labeled "Enormous Input Test" so it requires you to use some better/faster I/O methods
just replacing cout with printf and cin with scanf will give you an AC but to improve your execution time you need to use some faster IO method for example reading character by character using getchar_unlocked() will give you a better execution time
so you can read the values by using a function like this , for a better execution time.
inline int read(){
char c=getchar_unlocked();
int n=0;
while(!(c>='0' && c<='9'))
c=getchar_unlocked();
while(c>='0' && c<='9'){
n=n*10 + (c-'0');
c=getchar_unlocked();
}
return n;
}

The linked problem contains the following description:
The purpose of this problem is to verify whether the method you are
using to read input data is sufficiently fast to handle problems
branded with the enormous Input/Output warning. You are expected to be
able to process at least 2.5MB of input data per second at runtime.
Considering that, reading values from input a few bytes at a time using iostreams isn't going to cut it. I googled around a bit and found a drop-in replacement for cin and cout described on CodeChef. Some other approaches you could try include using a memory-mapped file and using stdio.
It might also help to look for ways to optimize the calculation. For example, if ti < k, then you know that k is not a factor of ti. Depending on the magnitude of k and the distribution of ti values, that observation alone could save a lot of time.
Remember: the fact that your code is short doesn't mean that it's fast.

Related

How to fix binary search algorithm?

Ok so i have been learning binary search. My teacher has given me a problem on codeforces and it always fails on test 2. Here is the problem:
In this problem jury has some number x, and you have to guess it. The number x is always an integer from 1 and to n, where n
is given to you at the beginning.
You can make queries to the testing system. Each query is a single integer from 1
to n
. Flush output stream after printing each query. There are two different responses the testing program can provide:
the string "<" (without quotes), if the jury's number is less than the integer in your query;
the string ">=" (without quotes), if the jury's number is greater or equal to the integer in your query.
When your program guessed the number x
, print string "! x", where x
is the answer, and terminate your program normally immediately after flushing the output stream.
Your program is allowed to make no more than 25 queries (not including printing the answer) to the testing system.
Input
Use standard input to read the responses to the queries.
The first line contains an integer n
(1≤n≤pow(10,6) — maximum possible jury's number.
Following lines will contain responses to your queries — strings "<" or ">=". The i
-th line is a response to your i-th query. When your program will guess the number print "! x", where x
is the answer and terminate your program.
The testing system will allow you to read the response on the query only after your program print the query for the system and perform flush operation.
Output
To make the queries your program must use standard output.
Your program must print the queries — integer numbers xi
(1≤xi≤n), one query per line (do not forget "end of line" after each xi
). After printing each line your program must perform operation flush.
And here is my code:
#include <iostream>
using namespace std;
int main()
{
int n;
string s;
int k=0;
cin>>n;
int min=1,max=n;
int a;
while(k==0)
{
if(max==min+1)
{
cout<<"! "<<min;
k=1;
break;
}
a=(min+max)/2;
cout<<a<<endl;
cin>>s;
if(s==">=")
min=a;
else
max=a;
}
}
I dont know what test 2 is, but i would be happy to hear ideas as to where my programs is wrong. My guess is its something with the number of guesses. Thanks in advance!
I have tried variations of the loop written above, but they all give the same result.

Time limit exceeded on test 10 code forces

hello i am a beginner in programming and am in the array lessons ,i just know very basics like if conditions and loops and data types , and when i try to solve this problem.
Problem Description
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.
Input Specification
The first line contains a single integer n (1⩽n⩽105) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'.
It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit 00 or "one" which corresponds to the digit 11.
Output Specification
Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.
Sample input:
4
ezor
Output:
0
Sample Input:
10
nznooeeoer
Output:
1 1 0
i got Time limit exceeded on test 10 code forces and that is my code
#include <iostream>
using namespace std;
int main()
{
int n;
char arr[10000];
cin >> n;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
for (int i = 0; i < n; i++) {
if (arr[i] == 'n') {
cout << "1"
<< " ";
}
}
for (int i = 0; i < n; i++) {
if (arr[i] == 'z') {
cout << "0"
<< " ";
}
}
}
Your problem is a buffer overrun. You put an awful 10K array on the stack, but the problem description says you can have up to 100K characters.
After your array fills up, you start overwriting the stack, including the variable n. This makes you try to read too many characters. When your program gets to the end of the input, it waits forever for more.
Instead of putting an even more awful 100K array on the stack, just count the number of z's and n's as you're reading the input, and don't bother storing the string at all.
According to the compromise (applicable to homework and challenge questions) described here
How do I ask and answer homework questions?
I will hint, without giving a code solution.
In order to fix TLEs you need to be more efficient.
In this case I'd start by getting rid of one of the three loops and of all of the array accesses.
You only need to count two things during input and one output loop.

How to change cout to printf in C++? or how to make the console application run faster?

I got a homework which goes through a compiler which checks if all is correct but it keeps giving result : "time limit exceeded" , the application works as it should in normal C++ compiler but I have to send the code to Themis which doesn't accept it due to "time limit exceeded"
Task :
Input:
In the first input line is given the integer t (1 ≤ t ≤ 100000) specifying the number of tests. Each test is given by three integers: a, b, m as defined above (1 ≤ a ≤ 10^9, 0 ≤ b ≤ 10^9, 1 ≤ m ≤ 10^6).
Output:
T lines should be printed. In each line, the answer to the query: (a^b)% m.
example of input data:
2
3 2 10
the correct answer is : 9
One friend told me to change cout to printf which might result in faster runtime but I'm not sure how to do it.
My code
#include <iostream>
using namespace std;
int main()
{
int t;
cin>>t;
for (int i=0; i<t; ++i)
{
int a,b,m;
long long int x,wynik=1;
cin>>a>>b>>m;
x=(long long int) a;
do
{
x%=(long long int)m;
if (b&1) {
wynik*=x;
wynik%=(long long int)m;
}
x*=x;
} while (b>>=1);
cout <<wynik<<endl;;
}
return 0;
}
Answering the literal question, how to change cout to printf.
Instead of #include <iostream>, you want #include <cstdio>, which is short for "C language standard input and output".
Instead of cout <<wynik<<endl;, you want printf("%d\n", (int) wynik). Here, "%d\n" is a formatting string saying "print the next argument, which should be int, in decimal, and then print a newline".
You may also want to use C-style input, then change cin>>a>>b>>m; into scanf("%d%d%d", &a, &b, &m);. This says "read three decimal integers, one into variable a (& is taking an address of a variable), the other into b, and yet another into m.
That said, note that relative speed of C-style and C++-style input and output depends on plenty of factors, including compiler version, OS, and environment. In another testing environment, you may find cout is actually on par with, or faster than, printf.
If you want to use cin and cout you can insert this lines in main()
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
and it should work as fast as priantf and scanf.

Printing a value changes the output of the code

Few hours ago, a competition was held on CodeForces , this was one the questions of the competition -
Problem C (You dont have to read/solve it to answer the question)
EDIT : Adding the question here as requested, again, one does not necessarily have to read it.
Slastyona and her loyal dog Pushok are playing a meaningless game that
is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in
each round, a natural number k is chosen. Then, the one who says (or
barks) it faster than the other wins the round. After that, the
winner's score is multiplied by k2, and the loser's score is
multiplied by k. In the beginning of the game, both Slastyona and
Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all
n games was recorded. She managed to recall the final results for each
games, though, but all of her memories of them are vague. Help
Slastyona verify their correctness, or, to put it another way, for
each given pair of scores determine whether it was possible for a game
to finish with such result or not.
Input In the first string, the number of games n (1 ≤ n ≤ 350000) is
given.
Each game is represented by a pair of scores a, b (1 ≤ a, b ≤ 10^9) –
the results of Slastyona and Pushok, correspondingly.
Output For each pair of scores, answer "Yes" if it's possible for a
game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
So I solved it, and after the competition was over, me and my friends were discussing the problems when they asked me what was my answer coming for the following test case -
1
1 1
I said it was "Yes" on my IDE (Dev-C++ 5.11), (as it was supposed to be)
But when we ran it on ideone, it came out to be "No" !!
I thought there must be a problem with my code only, so i tried debugging it when i came across this problem,
My Code -
#include<stdio.h>
using namespace std;
long long int iscube(long long int n)
{
long long int lo = 0;
long long int hi = 1000000;
while(lo < hi)
{
long long int mid = (lo+hi)/2;
if(mid*mid*mid < n)
lo = mid+1;
else
hi = mid;
}
return lo;
}
int main()
{
long long int a,b;
int n;
scanf("%d",&n);
while(n--)
{
scanf("%I64d %I64d",&a,&b);
long long int c = a*b;
long long int cb = iscube(c);
//printf("%lld",cb)
if(cb*cb*cb == c)
{
if(a%cb == 0 && b%cb == 0)
printf("Yes\n");
else
printf("No\n");
continue;
}
printf("No\n");
}
}
When i give the input as
1
1 1
in the above code, the answer comes out to be "No"
BUT if I ONLY uncomment the line above the if statement in the while loop in the main() function,
the answer would be "1 Yes"
(these outputs are the outputs i got when i ran the code on ideone, when running on Dev-C++ 5.11 , i got "Yes" and "1 Yes" as expected)
Now while i was thinking that my my answer of codeforces would be evaluated as WA, After the system test, it came out to be Accepted!
Does anyone have any idea on why this issue is arising?
(Also, could someone add the appropriate tags, if any)
Turn up your warnings, you have undefined behavior in your scanf:
warning: length modifier 'I64' results in undefined behavior or no effect with 'd' conversion specifier [-Wformat]
scanf("%I64d %I64d",&a,&b);
If you change it to scanf("%lld %lld",&a,&b); (C++11), then you'll have defined behavior, however since you're using C++, just use a stream instead:
std::cin >> a >> b;
Demo

How to make this code shorter to do faster

I am new c++ learner.I logged in Codeforces site and it is 11A question:
A sequence a0, a1, ..., at - 1 is called increasing if ai - 1 < ai for each i: 0 < i < t.
You are given a sequence b0, b1, ..., bn - 1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasing?
Input
The first line of the input contains two integer numbers n and d (2 ≤ n ≤ 2000, 1 ≤ d ≤ 106). The second line contains space separated sequence b0, b1, ..., bn - 1 (1 ≤ bi ≤ 106).
Output the minimal number of moves needed to make the sequence increasing.
I write this code for this question:
#include <iostream>
using namespace std;
int main()
{
long long int n,d,ci,i,s;
s=0;
cin>>n>>d;
int a[n];
for(ci=0;ci<n;ci++)
{
cin>>a[ci];
}
for(i=0;i<(n-1);i++)
{
while(a[i]>=a[i+1])
{
a[i+1]+=d;
s+=1;
}
}
cout<<s;
return 0;
}
It work good.But In a test codeforces server enter 2000 number.Time limit is 1 second.But it calculate up to 1 second.
How to make this code shorter to calculate faster?
One improvement that can be made is to use
std::ios_base::sync_with_stdio(false);
By default, cin/cout waste time synchronizing themselves with the C library’s stdio buffers, so that you can freely intermix calls to scanf/printf with operations on cin/cout. By turning this off using the above call the input and output operations in the above program should take less time since it no longer initialises the sync for input and output.
This is know to have helped in previous code challenges that require code to be completed in a certain time scale and which the c++ input/output was causing some bottleneck in the speed.
You can get rid of the while loop. Your program should run faster without
#include <iostream>
using namespace std;
int main()
{
long int n,d,ci,i,s;
s=0;
cin>>n>>d;
int a[n];
for(ci=0;ci<n;ci++)
{
cin>>a[ci];
}
for(i=0;i<(n-1);i++)
{
if(a[i]>=a[i+1])
{
int x = ((a[i] - a[i+1])/d) + 1;
s+=x;
a[i+1]+=x*d;
}
}
cout<<s;
return 0;
}
This is not a complete answer, but a hint.
Suppose our seqence is {1000000, 1} and d is 2.
To make an increasing sequence, we need to make the second element 1,000,001 or greater.
We could do it your way, by repeatedly adding 2 until we get past 1,000,000
1 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + ...
which would take a while, or we could say
Our goal is 1,000,001
We have 1
The difference is 1,000,000
So we need to to do 1,000,000 / 2 = 500,000 additions
So the answer is 500,000.
Which is quite a bit faster, because we only did 1 addition (1,000,000 + 1), one subtraction (1,000,001 - 1) and one division (1,000,000 / 2) instead of doing half a million additions.
Just as #molbdnilo said, Use math to get rid of the loop, and it's simple.
Here is my code, accepted on Codeforces.
#include <iostream>
using namespace std;
int main()
{
int n = 0 , b = 0;
int a[2001];
cin >> n >> b;
for(int i = 0 ; i < n ; i++){
cin >> a[i];
}
int sum = 0;
for(int i = 0 ; i < n - 1 ; i++){
if(a[i] >= a[i + 1]){
int minus = a[i] - a[i+1];
int diff = minus / b + 1;
a[i+1] += diff * b;
sum += diff;
}
}
cout << sum << endl;
return 0;
}
I suggest you profile your code to see where the bottlenecks are.
One of the popular areas of time wasting is with input. The fewer input requests, the faster your program will be.
So, you could speed up your program by reading from cin using read() into a buffer and then parse the buffer using istringstream.
Other techniques include loop unrolling and optimizing for data cache. Reducing the number of branches or if statements will also speed up your programs. Processor prefer crunching data and moving data around to jumping to different areas in the code.