Packaging Cupcakes-Time limit exceeded error

I changed cin/cout to scanf/printf but still it gives me time limit exceeded error.Can someone please tell me how to rectify it?

#include <stdio.h>
#include <iostream>

using namespace std;

int main()
{

int t,a,max,rem,i;

   scanf("%d",&t);

   rem=0;

   while(t>0)

    {

        scanf("%d",&a);

        for(i=2;i<=a;i++)

          {

              if(a%i>=rem)

                {

                    rem=a%i;

                    max=i;

                }

          }

        printf("%d\n",max);

        t--;

    }
   
   return 0;

}

#include <stdio.h>
#include
using namespace std;

int main()
{
    int t,a,max,rem,i;
    scanf("%d",&t); rem=0;
    while(t--)
    {
        scanf("%d",&a);
        for(i=2;i<=a;i++)
        {
            if(a%i>=rem)
            {
                rem=a%i; max=i;
            }
        }
        printf("%d\n",max);
    }
    return 0;
}

First of your program is giving wrong output see here… the reason for TLE is that you are looping from 2 to a, since the amount of input will be large the O(n) approach you followed fails… the desired answer is always half of given n plus 1… for reference see my solution

you don’t have any need to make a loop for every test case,thats why u r getting TLE. Every test case should be proceed in O(1).

2 Likes

thank you…i din’t realise this method so i ran a loop for each number.