We Recommend

Java How to Program Java How to Program
Takes a new tools-based approach to Web application development that uses Netbeans 5.5 and Java Studio Creator 2 to create and consume Web Services. Features new AJAX-enabled, Web applications built with JavaServer Faces (JSF), Java Studio Creator 2 and the Java Blueprints AJAX Components. Includes new topics throughout, such as JDBC 4, SwingWorker for multithreaded GUIs, GroupLayout, Java Desktop Integration Components (JDIC), and much more.


Posted By

gdonald on 09/27/06


Tagged

number generator prime


Versions (?)


Java prime number generator


Published in: Java 


  1. package com.destiney.Prime;
  2. class Prime
  3. {
  4. public static void main( String args[] )
  5. {
  6. int x, y, c = 0;
  7. for( x = 2; x < 1000; x++ )
  8. {
  9. if( x % 2 != 0 || x == 2 )
  10. {
  11. for( y = 2; y <= x / 2; y++ )
  12. {
  13. if( x % y == 0 )
  14. {
  15. break;
  16. }
  17. }
  18.  
  19. if( y > x / 2 )
  20. {
  21. System.out.println( x );
  22. c++;
  23. }
  24. }
  25. }
  26. System.out.println( "\nTotal: " + c );
  27. }
  28. }

Report this snippet 

Comments

RSS Icon Subscribe to comments
Posted By: jfurnish on December 18, 2006

Thanks works great!

Posted By: dreadrx7 on January 4, 2007

This works great but I need one that uses arrays. Thanks anyway

Posted By: sky on October 9, 2007

This might help!!

/** * */ package main; import java.util.Arrays;

/** * @author Shri Krishan Yadav * This program find and displays prime numbers between 1 and a given number. * It doesn't include the number entered. */ public class PrimeNumbers {

/**
 * @param args
 */
public static void main(String[] args) {
    if(args.length==0)
    {
        System.out.print("Please ennter a Number.");
        System.exit(0);
    }
    int count=0;
    int number= Integer.parseInt(args[0]);
    int[] numColl= new int[number];
    for (int i=1;i<number;i++)
    {
        if(i==1)
        {
            continue;
        }
        else if(i==2||i==3||i==5||i==7)
        {
            count++;
            numColl[i]= i;
            continue;
        }
        else
        {
            if(i%2==0||i%3==0||i%5==0||i%7==0)
                continue;
            else 
            {
                numColl[i]= i;
                count++;
                continue;
            }
        }
    }
    Arrays.sort(numColl);

    System.out.println("Prime numbers between 1 and "+number+" are "+ count);
    int N=1;
    for(int i=0;i<numColl.length;i++)
    {
        if(numColl[i]==0)
            continue;
        else
        {
            System.out.println("Prime number " +N+ " is: "+numColl[i]); 
            N++;
        }

    }

}

}

You need to login to post a comment.