why this code is giving a time limit exceeded problem?

#include <stdio.h>

int main()
{
	long long int n;
	long long int k;
	long long int a[1000000];
	int i;
	int count;
	count = 0;
	scanf("%lld", &n);
	scanf("%lld", &k);
	for(i = 0; i < n; i++) {
		scanf("%lld", &a[i]);
		}
	for(i = 0; i < n; i++) {
		if (a[i]%k == 0)
			count++;
	}
	printf("%d\n", count);

	return 0;
}

@ayush_awasthi I believe you are trying to solve Enormous Input Test problem. Now here are few things wrong with your solution.

  • Problem statement clearly states that n k (n, k<=107) , no need to use long long int , int will suffice.
  • You are declaring too much stack memory inside main function. Any large arrays should be declared globally, outside of any functions - putting an array of 100000 ints inside a function probably won’t work. And this problem can be solved without using array, perform division operation by K when you read an integer and increment count accordingly.

Do these changes and you will be good to go. If you still face any problems, I’m Here :).

Thanks & Regards

CrucifiX

4 Likes

You are comparing int i with long long int n. If the value of n is larger than range of int then condition will be true always and it will stuck in infinite loop causing Time Limit Exceeded.

I believe that is not true. First value of N will never be greater than 10^7 as per constraint and second you can compare an integer with long long int, eg. http://ideone.com/KRD56J

even then also it did not work!

@crucifix I agree that they can be compared but I said for large value of n (greater than range of int) the comparison will yield true always. Besides I didn’t read problem statement and constraints and I replied in general not specific to this problem only.