Question :
Write a function named minPrimeDistance that returns the smallest distance
between two prime factors of a number. For example, consider 13013.
Its prime factors are 1, 7, 11, 13 and 13013. minPrimeDistance(13013) would
return 2 because the smallest
distance between any two prime factors is 2 (13 - 11 = 2). As another example, minPrimeDistance (8) would return 1 because the prime factors of 8 are 1, 2 and the
smallest distance between any two factors is 1 (2 - 1
= 1). Note: Consider 1 as a prime
number.
The function signature is
   int minPrimeDistance(int
n)
Solution :
  public static int
minPrimeDistance(int n)
        {
            int minDist
= n, count = 0, f1 = 0;
            bool isPrime = true;
            for (int i = 1; i <= n; i++)
            {
                if (n % i
== 0)
                {
                    for (int j = 2; j <= i / 2; j++)
                    {
                        if (i % j == 0)
                        {
                            isPrime = false;
                            break;
                        }
                    }
                    if (isPrime)
                    {
                        if (count == 0)
                            f1 = i;
     
                  count++;
                        if (count > 1)
                        {
                            if (minDist > i - f1)
                                minDist = i -
f1;
                            f1 = i;
                        }
 
                  }
                }
            }
            return minDist;
        }



 03:34
03:34


 

i think code this code is complex some how
ReplyDelete#can we optimize this with below code
public static int minDistance(int num){
int fact1 = 1;
int minDist = num;
for(int i=2; i<num; i++){
if (num%i==0){
if((i-fact1)<=minDist){
minDist = i-fact1;
fact1 = i;
}
}
}
return (minDist);
}
hey man ! you are wrong with the given question tho.
ReplyDelete-----this in other methode --------------
ReplyDelete------------------------------------------
static int minDistance(int nbr){
int fi=1,count=0,minDis=nbr;
for(int i=1;i<=nbr;i++){
if(nbr%i==0){
if(count==0)
fi=i;
count++;
if(count>1){
if(minDis>i-fi){
minDis=i-fi;
fi=i;
}
}
}
}
return minDis;
}
----------------------------------------
----------------------------------------
the code doesn't work for negative numbers
ReplyDeleteyou must check for negative values and change them to +ve
ind it also returns wrong values for 1 and 0;
static int minprimedistance(int n) { int min=n;
ReplyDeletefor(int i=1; i<=n; i++){ if(n%i==0 && isPrime(i)){ for(int j=i+1; j<=n; j++){ if(n%j==0 && isPrime(j)){ if(min>j-i)
min = j-i;
break; } } } }
return min;
}