Here you will find solutions of many problems on spoj. If you want solution of some problem which is not listed in blog or have doubt regarding any spoj problem (which i have solved) or any programming concept (data structure) you can mail me @ raj.nishant360@gmail.com

And my humble request to you all that don't copy the code only try to understand the logic and algorithm behind the code. I have started this because if you tried as hard as you can and still can't find any solution to the problem then you can refer to this.
You can read my answer how to start competitive programming CLICK HERE

Saturday, February 22, 2014

HG-HUGE GCD

HUGE GCD

below given code is for hg spoj or huge gcd spoj.
in this question simple logic is that gcd of two number whose products are given is the gcd of each pair of products.
eg:
2 x 3 x 5=30;
4 x 5=20;
gcd (20,30)=10;
this can be obtained as number of common prime terms in both products
we can write above as
2 x 3 x 5=30;
2 x 2 x 5=20;
now common terms are 2 x 5 =10;
this is logic of gcd studied in 5 or 6th standerd
#include <stdio.h>
#include <iostream>
using namespace std;
long gcd(long a,long b)
{
 return b==0?a:gcd(b,a%b);
}
long a[1009];
long b[1009];
long store[1000000];
int main()
{
 int n,m;
 scanf("%d",&n);
 for(int i=0;i<n;i++)
  scanf("%ld",&a[i]);
 scanf("%d",&m);
 for(int i=0;i<m;i++)
  scanf("%ld",&b[i]);
 int k=0;
 long g;
 for(int i=0;i<n;i++)
 {
  for(int j=0;j<m;j++)
  {
   g=gcd(a[i],b[j]);
   if(b[j]!=1 && g!=1){
    store[k++]=g;
    a[i]=a[i]/g;
    b[j]=b[j]/g;
   }
  }
 }
 long long temp,carry;
 long total=1;
 int flage=0;
 int res[10]={0};
 res[9]=1;
 for(int i=0;i<k;i++)
 {
  carry=0;
  total*=store[i];
  if(total>999999999){
   flage=1;
  }
  for(int j=9;j>=1;j--)
  {
   temp=res[j]*store[i];
   res[j]=(temp + carry)%10;
   carry=(temp + carry)/10;
  }
 }
 if(flage)
 for(int i=1;i<=9;i++)
  printf("%d",res[i]);
 else
  printf("%ld",total);
 printf("\n");
 return 0; 
}

No comments:

Post a Comment

Your comment is valuable to us