Search code examples
greatest-common-divisor

This is spoj's Playing with gcd id najpwg http://www.spoj.com/problems/NAJPWG/


I'm getting tle in this code any suggestions.I'm calculating the sum n/i where n is the input and i goes from 2 to n. for example for 5 pairs will be (2,2),(3,3),(4,4),(5,5),(2,4)

#include<stdio.h>

int main()
{
int i,j,t,n,m;
long long k;
scanf("%d",&t);
for(i=0;i<t;i++)
{
    scanf("%d",&n);
    m=n/2;
    k=0;
    for(j=2;j<=m;j++)
    {
        k+=(n/j);
    }
    k+=(n-m);
    printf("Case %d: %lld\n",i+1,k);
}
return 0;
}`

Solution

  • There are a lot of problems with your code.

    Broadly classifying -

    1. Optimization can be talked about when the issue no.2 gets resolved.

    2. Code gives wrong answer. Your algorithm is,summarily, incorrect. Dump this approach and think in terms of "Euler Totient" and elementary dynamic programming.

    For example,

     Let's say,  the number is N.
    

    Now, N would contain all the pairs that N-1 had. In addition to that it would also contain some newer ones( for which you can take help of Euler Totient function).

    Sample Test cases for your practice -

    input-
    25
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    1021
    99998
    99999
    100000
    
    output-
    Case 1: 0
    Case 2: 0
    Case 3: 1
    Case 4: 2
    Case 5: 4
    Case 6: 5
    Case 7: 9
    Case 8: 10
    Case 9: 14
    Case 10: 17
    Case 11: 23
    Case 12: 24
    Case 13: 32
    Case 14: 33
    Case 15: 41
    Case 16: 48
    Case 17: 56
    Case 18: 57
    Case 19: 69
    Case 20: 70
    Case 21: 82
    Case 22: 204311
    Case 23: 1960304047
    Case 24: 1960339246
    Case 25: 1960399246
    
    *