Monday, 11 March 2013

Prime Number source code | C#.Net | Prime Number from 1 to n..with examples and comments


 source code how to calculate prime number in c#.net.With valid and correct output.
Definition Of Prime Number:- The number which is divisible by 1 and itself.
or we can say prime number is a number which has only two factor first one is 1 and second
is that number itself.
 in this article i have shown to calculate prime number from one range to n range and also how to find
simple number  is prime or not.


Now first to calculate whether entered number is prime number or not.
here is code:- on page init


   
    protected void Page_init(object sender, EventArgs e)
    {
           
        int num=20, flag=0;
     
     
        for (int i=2;i<;num/2++)//i will be less than half of number it will also work.
        {
          if(num%i==0)
          {
          flag=1;   // now entered number 20 is divisible by 2 means 20 has another factor that is 2
so , it  is not prime number no need to go in execution use break statement.
          break;
         
          }
          else
          {
          flag=0;
          }
        }
        if (flag==0)
        {
          Response.Write(" +num+"is  not prime number :-");
        Response.Write("</br>");
        }
else
{

 Response.Write( +num+"is  a  prime number :-");
}

       
     


    }
}


It was simple program to check number is prime or not now i want to check number from n to n+...
or 1 to 20 , 1 to 100 , 1 to 1000 just enter num=100 or num=1000 as you want range.

   
    protected void Page_init(object sender, EventArgs e)
    {
           
        int num=20, flag=0;
        Response.Write("Prime Number from 2 to" +num+"is :-");
        Response.Write("</br>");
        for (int j=2;j<num;j++)
        {
        for (int i=2;i<j;i++)
        {
          if(j%i==0)
          {
          flag=1;
          break;
         
          }
          else
          {
          flag=0;
          }
        }
        if (flag==0)
        {
        Response.Write(j);
         Response.Write("</br>");
        }
       
        }


    }
}


Prime Number from 2 to 20 is :-
2
3
5
7
11
13
17
19



0 Comments: