Frage

I am coding to find the number of common divisors of two numbers n and k.

I am implementing it using the approach of finding the GCD g and then finding the number of divisors of the GCD.

However the code compiles but gives a not responding message on running :(

I have blown my head off on this.. can anyone please help in debugging.. Thanks in advance

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>

using namespace std;

vector<bool>p(1000002,true);

long int getgcd(long int a, long int b)
{  if(b == 0)
          return a;
   else
          return getgcd(b, a % b);
}

void prime()
{   int i,j;
    for(i=2;i<1000001;i++)
      if(p[i])
        for(j=i*i;j<1000001;j=j+i)
             p[j]=false;
    p[0]=false;
    p[1]=false;
}

void divfind(long int a, long int b)
{
     long int g;
     g = getgcd(a,b);
     int i,s,j=0,ans=1,num=0;
     //short int fo[1000000];
     s=(int) sqrt(g);
     for(i=2;i<s+1;i++)
       if(p[i])
        {
          while(g%i==0)
          {g=g/i;
           num++;
          }
          if(num)
            ans*=++num;
          num=0;
        }
      printf("%d\n",ans);
}

int main()
{
    prime();
    long int n;
    int q;
    scanf("%ld %d",&n,&q);
    while(q--)
    {
        int t;
        long int k;
        scanf("%d%ld",&t,&k);
        if(t==1)
        divfind(n,k);
//        else if(t==2)
//       divi(n,k);
//        else
//        nodivi(n,k);
    }
    return 0;
}
War es hilfreich?

Lösung

You're running into integer overflows - i*i is only safe up to i=46340 (~2^15*sqrt(2)) with 32 bit integers, e.g:

i     i*i
46339 2147302921
46340 2147395600
46341 -2147479015
46342 -2147386332

This leads to undefined behaviour.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top