0
votes

I'm suffering from one problem on codechef.com.

When I submit my code with all variables (which are only 3) in global declaration, I get Accepted, but when I move all 3 variables inside main function, I get wrong answer!! All 3 variables are long long type and IO used is scanf & printf.

long long P, Q, a; scanf("%d %d",&P,&Q); printf("%lld",a);

I'v tried same code translated in pascal, then I get Time limit exceed.

Also one thing, when I use my custom fast IO functions, I get Time limit exceed.

In all cases my code works fine and produce correct output in my IDE.

When I use global variables and don't write "return 0" statement though it gets accepted. But if I declare variables inside main function and don't write "return 0" statement, it stuck with non zero return code runtime error.

Can anybody tell why I'm not able to get my code accepted in case of local variable declaration or why I'm getting time limit exceed when used exact algo in Pascal?? Is there something wrong with input or something??

Here is my C code which gets accepted by codechef:

#include<stdio.h>
long long P,Q,a;
int main()
{
    scanf("%d %d",&P,&Q);
    //read(Q);
    while (P>0 || Q>0 )
    {
        a = (  Q * ( 3*P - 2*(Q*Q-1) )  ) / 3;
        printf("%lld\n",a);
        scanf("%d %d",&P,&Q);
    }
    return 0;
}

And this is pascal code which gets Time limit exceed:

program ex2dimarray;
var
   P,Q,a: Cardinal;
begin
     readln(P,Q);
     //read(Q);
     while (P>0) or (Q>0) do
     begin
          a := (  Q * ( 3*P - 2*(Q*Q-1) )  ) DIV 3;
          writeln(a);  
          readln(P,Q);
          //read(Q);
     end;
end.

Program termination condition is both P and Q is 0.

1
Use <inttypes.h> and scanf("%"SCNd64" %"SCNd64, &P, &Q);. - Brian Cain
But why I'm getting Time limit exceed in Pascal??? - avg598
You haven't shown any example ("equivalent") Pascal code. But you've likely found some Pascal undefined behavior. - Brian Cain
You need to provide more code, both C and Pascal, and what is the acceptance criteria you're trying to meet? - Mike
@avg598 You're using readln incorrectly in Pascal. You cannot call it with two arguments unless you're reading from a file. freepascal.org/docs-html/rtl/system/readln.html - JoshB

1 Answers

1
votes

For the C code, your problem is with your scanf. Using %d instead of %lld when writing to a long long int would result to just taking an int and storing it into long long int. For global variables with small input, this doesn't matter as globals are initialized to 0. But when you put them inside main, the upper bytes that are not written to by scanf might contain some random data which will cause your computation to be unpredictable.