Saturday 9 April 2016

PRIME1 - Prime Generator

Ok, so our next problem is loosely based on those sort of problems where we had to print all the prime numbers till first N numbers. 

Here is the problem link, http://www.spoj.com/problems/PRIME1/

--------------------------------------------------------------------------------------------------------------------------

Lets  take the problem bit by bit,one thing at a time.

INPUT:
First of all, we have to input the no. of test cases(t<=10). So, this part is easy.

Next, we have to enter two integers(1 <= m <= n <= 1000000000, n-m<=100000) separated by space for each test case, these two integers will be the extremities between which we have to find out the prime numbers.This input part is easy as well, take a loop while test case turns 0,keep on decrementing test case and input m & n for each test case till the loop ends. You will have to use arrays of m & n to make this work for obvious reasons. Make the array m[15],n[15] even though we need only m[10] & n[10], to avoid running into runtime error.

OUTPUT:
For the output part,we can use nested loops or functions. This will be a bit tricky. You got to try something like,start from m,then check from every integer starting from 1 and going on till?? m?. No, the trick here is that, if a given no. x is not divisible by 2 then if it is not a prime number ,then its factor will be less than x/2(because ofcourse,since 2 isnot a factor,so for no.s greater than or equal to x/2,they will have to be multiplied by a number y,so that x/2*y=x . Clearly, y won't be an integer). Hope you understand this. Lets try writing something by using it.

REMEMBER, using lots of nested loops increases time consumed by your code,using functions increases the size of your code.

TWEAKED FIRST & WORKING SOLUTION:-
#include <stdio.h>
int prime(int); --->Function prototype
int main()
{
int t,m[15],n[15],a,c=0; //like i mentioned above, arrays of m and n  
scanf("%d",&t);
a=t;
while(a>0)
     {
      scanf("%d %d",&m[c],&n[c]); /*stores value of m and n for each test case*/
      c++;
      a--;
      }
while(a<t)
    {
     while(m[a]<=n[a])
        { 
         prime(m[a]);
         m[a]++;
         }
    a++;
    printf("\n");
    }
return 0;
}
int prime(int n){int x=2,y=1,z;
z=n/y;
if(n==1) return n;

else if (n==2) 

{printf("%d\n",n);return n;}

else {
          while(x<z)
                  {
                   if(n%x==0) return n;
                   x++;
                   y++;
                   z=n/y;
                   }
         printf("%d\n",n);
}
return n;
}

The rest of the code is pretty self explanatory. There may be parts which you didn't get. Please leave comments. I always have time for more questions.

No comments:

Post a Comment