Pages

Wednesday 26 September 2012

UVA - 11417 - GCD

#include <stdio.h>

int GCD(int i,int j){
    if (j==0)
        return i;
    return GCD(j, i % j);
}

int main()
{   int cases,i,j;
    int G[501];

    //using a DP approach
    G[0]=0;
    G[1]=0;
    for(cases=2;cases<501;cases++){
        G[cases]=G[cases-1];
        for(i=1;i<cases;i++){
            if(i<cases-1){
                G[cases]+=GCD(i,cases);
            }else{
                for(j=i+1;j<=cases;j++){
                    G[cases]+=GCD(i,j);
                }
            }
            }
    }
    while(1){
        scanf("%d",&cases);
        if(cases==0)
            break;
        printf("%d\n",G[cases]);
    }
       return 0;
}

No comments:

Post a Comment