How to get prime numbers!

Let we have to find out n terms of prime numbers. We will not use any built-in functions. Using fully raw codes we will do this. Although I have done this using PHP, the other languages also applicable in this tricks. You need to change the commanding operators only when you will use another languages.


Let us think the procedure and do step by step. 

 Note: You may not be allowed to copy code from this site. If you need click here to download this full code.

We will generate the HTML form to accept/obtain the starting number and the length of the series. Means that from which or after which number we will start our operation and how long we will do? This informations will be collected from here.

<form action='?' method='POST'> 
Enter the startig number: <input name="start" /><br/> 
Enter the series length: <input name="length" /><br/> 
<input type='submit' value='Generate'/> 
</form>
<hr/>

Now we will make a function which will convert any number into integer. That means the part after the point of the number will be removed. Because we know the prime numbers are the integer numbers. And another secret tips is here. You will find in the next operation. However, create this function.


function get_int($n)
{
 $n = explode(".",abs($n));
 return $n[0];
}

This time is to make another function. This function will check whether any function is prime or not! Why are we using the functions? It may be your question. We are using functions because we have to call them continuously. So if we use any other loop it will take much code and much more times. So we will build this function also.

function isprime($n)
{
 $n = get_int($n);
 if($n==1 or $n==2)
  return true;
 for($i=2;$i<=get_int($n/2);$i++)
 {
  if(get_int($n/$i)*$i == $n) return false;
 }
 return true;
}

Now the term of printing the series. Just check whether the current number is prime or not. Increase it again and again until the length of series is reached. You can use any loop here or make any function as your wish.

while($counter<$length)
{
 if(isprime($start))
 {
  echo "$start,";
  $counter++;
 }
 $start++;
}

That is all. Try to understand.

 Note: You may not be allowed to copy code from this site. If you need click here to download this full code.

Happy Programming.

Related Posts
Previous
« Prev Post