Tuesday, February 5, 2013

Find The Prime Numbers on Java programming language

When the loop control variable will not be needed elsewhere, most Java programmers declare it inside the for. For example, here is a simple program that tests for prime numbers. Notice that the loop control variable, i, is declared inside the for since it is not needed elsewhere.



// Test for primes.
class FindPrime { 
public static void main(String args[]) { 
  int num;  
  boolean isPrime;

    num = 14;

    if(num < 2)
              isPrime = false; 

   else
             isPrime = true;

    for(int i=2; i <= num/i; i++) { 
    if((num % i) == 0) {

        isPrime = false;
        break;

        }
    }

    if(isPrime)

                System.out.println("Prime");
    else
               System.out.println("Not Prime");
    }
 }

No comments:

Post a Comment