Help me getting prime numbers

hi,
can anyone help me with this i'm newbie and can't figure the solution out
"Write a multithreaded Java program that outputs prime numbers.
This program should work as follows: The user will run the program
and will enter a number on the command line The program will then
create a separate thread that outputs all the prime numbers less than or
equal to the number that the user entered".
thx in advance

prime numbers are numbers that can only be divided by 1 and itself
1,2,3,5,7,9,11,...
maybe the only condition u can check is whether it is divideable by 2 , 3 or 5 but you have to exclude 2 ,3 and 5
since all numbers (except prime numbers) are made up from multiplication from 2, 3 ,and 5, you can use that logic
example :
4 <-- divideable by 2 <-- not prime
9 <-- divideable by 3 <-- not prime
23 <-- not divideable by 2 , 3 , or 5 <-- then it is prime
if(nums == 2 || nums == 3 || nums == 5)
     //it is prime for sure
else if(nums % 2 == 0 || nums % 3 == 0 || nums % 5 == 0)
     //it is not prime
else
   // it is prime number

Similar Messages

  • Need help with finding prime numbers

    I have seen this question asked several times so i apologize for asking once again but I am very new to programming and could use some help. I know the way I have the extra if statements is not at all efficient but I cannot seem to figure out how to get a nested for statement with a divisor to work. The error I'm getting with this current code is that the second for statement needs to be boolean.
    package primenumbers;
    * @author Owner
    public class Main {
         * @param args the command line arguments
        public static void main(String[] args) {
            int primecount; //running total of prime numbers
            int incrementer; //increment numbers
            int sqrtInc; //square root of current increment
            int divisor;
            //set variables to 0
            primecount =0;
            incrementer=3;
            sqrtInc = (int)Math.sqrt(incrementer);
            divisor = 0;
         //print 2
            System.out.println("2");
         for(incrementer = 3; incrementer < 10000; incrementer = incrementer + 1 )
                     if (incrementer % 2 != 0)
                  if (sqrtInc % 3 != 0)
                     if (sqrtInc % 5 != 0)
                          if (sqrtInc % 7 != 0)
                              if (sqrtInc % 9 != 0)
                                  if (sqrtInc % 11 != 0)
        for (divisor = 3; divisor = incrementer; divisor = divisor +1)
                                  if ( incrementer % divisor !=0)
                  if (incrementer % (Math.sqrt(incrementer)) != 0)
              System.out.println(incrementer);
        }

    aeakers wrote:
    I thought I had described it. I appreciate the help but it seems pretty clear to me what this program is supposed to do.Yes, what it's supposed to do is clear: It's supposed to find some prime numbers.
    What's not clear, and what I'm asking about, is what algorithm you're trying to use. There's more than one way to find primes, and they all start with no regard whatsoever or any programming language. Then they get implemented in a programming language. It's not clear at all from that mess of code what algorithm you're trying to implement.
    And especially in the followup posts. Nope. Nothing was clarified there.
    Program should list every prime number that is less than 10000.
    I have it to check if the modulus is not zero for the following conditions:
    -divided by 2
    -square root divided by 3
    -square root divided by 5
    -square root divided by 7
    -square root divided by 9
    -square root divided by 11Why those particular numbers?
    Then check the modulus is not zero for the following
    number divided by a second number that increases up to the first numberI think I kind of get what you're saying here, but I don't think you understand it well enough to translate it to Java.
    I am really trying to get you the information you need but I am not at all familiar with this.The point here is that programming is as much about clarity and specificity of thought and communication as it is about the mechanics of the language. If you can't clearly and precisely express what you're trying to do--without regard to any programming language--then you won't be able to program it.
    At the very least, if you can't find a way to express your algorithm clearly and precisely, then you ought to put print statements in at each step of your program so you can see exactly what's happening each step of the way, compare that to what you think should be happening, and then find out where you're going wrong.
    Also, as a point of best practice, you should alaways use braces for if, for, etc., even when they're not strictly necessary.
    // bad
    if (...)
      singleStatement();
    // good
    if (...) {
      singleStatement();
    }

  • Help creating an applet (prime numbers and numbers divisible by 4)

    Hi all,
    I am very new to java, and I have exhausted all of my resources before posting here. I have checked the archives but what I am looking for is not really there. I have an exam in 2 days, and there is a question like this one I cannot get to work.
    I am supposed to ask for two numbers, the startNumber and endNumber. Then I am supposed to print in ascending or ascending order (this is already done)only the numbers divisible by 4 and the prime numbers. I have seen in the archives how you can use a boolean to check for prime numbers, but given the complexity of this question, I cannot put it into practice. Anybody can help me please?
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    public class Div4OrPrime extends Applet implements ActionListener
        //DECLARE THE GUIS
        public Button showB;
        public Label startL, endL;
        public TextField startN, endN;
        private TextArea screen;
        //DECLARE THE PANELS
        public Panel topPanel, middlePanel, bottomPanel;
        //DECLARING THE VARIABLES
        public int startNumber, endNumber;
        public int result;
        public String output="";
        public int counter;
        //INITIALIZATION OF THE APPLET
        public void init()
            //CREATION OF THE BUTTONS
              showB = new Button ("Show numbers");
           //CREATION OF LABELS
               startL = new Label ("Starting Number");
               endL = new Label ("Ending Number");
           //CREATION OF THE TEXTAREAS
              startN = new TextField(8);
              endN = new TextField(8);
              screen=new TextArea();   
           //CREATION OF THE PANELS
             topPanel=new Panel (new GridLayout (1,1));
             middlePanel = new Panel (new GridLayout (1,4));
             bottomPanel = new Panel (new GridLayout (1,1));
             setLayout (new GridLayout (3,3));
           //ADDING THE WIDGETS TO THE PANELS
              topPanel.add(showB);
              middlePanel.add(startL); middlePanel.add(startN);
              middlePanel.add(endL); middlePanel.add(endN);
              bottomPanel.add(screen);
              add(topPanel);
              add(middlePanel);
              add(bottomPanel);
           //ADD THE ACTION SOURCE LISTENER
              showB.addActionListener(this); 
              startN.addActionListener(this);
              endN.addActionListener(this);
          //SET THE ACTION
           public void actionPerformed(ActionEvent e)
               output="";
               if (e.getActionCommand().equals("Show numbers"))
           startNumber=Integer.parseInt(startN.getText());
                      endNumber=Integer.parseInt(endN.getText());
                   if  (startNumber<endNumber)
                      for (a = startNumber  ; a<=endNumber; a++)
                               output= output +a+"\n";
                               screen.setText(output);         
                          else if (startNumber>endNumber)
                              for (a=startNumber; a>=endNumber; a--)
                               output= output +a+"\n";
                               screen.setText(output);         
                         repaint();
    }

    Hi all,
    Iam very new to java, and I have exhausted all of my
    resources before posting here. I have checked the
    archives but what I am looking for is not really
    there. I have an exam in 2 days, and there is a
    question like this one I cannot get to work.
    I am supposed to ask for two numbers, the startNumber
    and endNumber. Then I am supposed to print in
    ascending or ascending order (this is already
    done)only the numbers divisible by 4 and the prime
    numbers. I have seen in the archives how you can use a
    boolean to check for prime numbers, but given the
    complexity of this question, I cannot put it into
    practice. Anybody can help me please?
    Code SNIP
    I'm sure there are better ways than this but it's the only one I can think of offhand.
    Create a boolean array from 2 to the largest number, set them all to true, then go through and on the first true number set all the multiples to false. Then do the same with the next true number(Sieve of Erasthoenes). Then you can go through and set all the mutiples of 4 to true with another loop. Then print the numbers in the range.

  • I am having trouble getting a numbers spreadsheet to hold different formats in the same column.  A column with a date formatted heading will not convert to $ for the cells below.   Any suggestions would help.

    I am having trouble getting a numbers spreadsheet to hold different formats in the same column.  A column with a date formatted heading will not convert to $ for the cells below.   Any suggestions would help.

    Hi Wayne,
    Thank you for this response.  I have tried this but when I start enterring $ amounts some, such as $6.00, go in OK others such as $4.00 appear as a date ie 4 Oct 12.  
    Kind regards
    Paul

  • Is there an app and/or is it possible to get the numbering back on the photos in the camera roll...separating by dates does not help me...need the numbers back!

    I run a food blog page and have over 2000 photos that were numbered before the previous update.  I depended on the numbers of my camera roll...is there an app and/or a way to get the numbers to show on the photos again?  Ugh!

    In the Photos app itself no, not unless you edit the photos and add a number onto them. There are third-party photos apps which can view the photos in the Photos app and show you their filenames e.g. PhotoMeta, or there are photo management apps such as Photo Manager Pro which you could use instead of the Photos app - you can copy photos to that app from the Photos app, and it shows their filenames

  • Creating a Program for Identifying Prime Numbers

    I am beginning computer science major and I am completely lost with this. Can anyone help me figure this out?
    Due: Monday, January 14, 10:00 am
    Write a program that calculates all prime numbers less than 10,000. The program works as follows:
    1. Create a main method, and a method called ArrayList< Integer > sieve( int n ), which returns a list with all the prime numbers less than n. The main method calls sieve( 10,000 ), and prints out the results.
    2. Inside of sieve(), do the following:
    a. Call method createTrueArray( n ) to create a boolean array of size n.
    b. Set cells 0 and 1 of the array to false. Each cell in the array represents a number, the boolean value represents whether it is prime or not. We start by assuming that all numbers greater or equal 2 are prime, and then we remove the ones that are not.
    c. Loop over the array, starting at index 2.
    d. First, remove all multiples of 2, by setting the values for 4, 6, 8, ... to false.
    e. Then, look for the next number still marked true (in this case 3), and set all its multiples to false.
    f. Repeat with all numbers that are marked true. When you are done, only prime numbers will be marked true.
    g. Call method booleanArrayToIntList() to return a list of integers that contains the primes.
    3. Method boolean[] createTrueArray( int n ) creates a boolean array of size n and initializes all its values to true.
    4. Method ArrayList< Integer > booleanArrayToIntList( boolean[] booleans ) loops through booleans, and for each true value, it adds the corresponding number to a list. Finally, it returns the list.

    brriney wrote:
    I am beginning computer science major and I am completely lost with this. Can anyone help me figure this out?
    Due: Monday, January 14, 10:00 am This is what I felt like typing in response to your post:
    Thank you for posting your assignment and telling us when it is due. Now please sit back, kick your feet up, have some donuts while we work on your homework.
    But I won't ;). Let me tell you just this. Dumping the assignment here without showing any work (and giving a deadline no less!) is tantamount to asking the volunteers here to do your assignment and will only get you flamed. We will help those that show some effort; so please please show your work and ask specific questions regarding your code.
    Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
    &#91;/code]

  • How do I get the Numbers application iOS 7.0.4 unstuck updating on iPad 2?

    How do I get the Numbers application unstuck in updating on iPad 2?   After the last update of iOS 7 it started acting up. Then weeks ago (in November) I opened the application right after iOS 7.0.4 update and while accessing a file it got stuck, some files are white and I can access them. Other files are gray and I can not open them. The application goes white when it first opens up instead of just opening then there is a delay, then it eventually opens.  It is stuck updating.
    I have tried various things. 1) Rebooting, 2) hard reboot (holding down the off button and home key until the apple icon appears), 3) tried putting it in Airplane mode-reboot-then connect to computer and iTunes-then rebooted. 4) tried opening a file in another application- I get an error message that says : can't open spreadsheet- this spreadsheet is updating, wait for it to finish then try opening. 5) sending spreadsheet- I get an error message that says : this spreadsheet is updating, wait for it to finish then try sending.  None of these have worked.
    I am at my wits end I use these files for my business and I am self-employed, some files I can't access at all, this is very serious for me. If you know how to fix this please help me.  I transferred all of my NECESSARY and IMPORTANT client files to Numbers from Excel, I've been using Numbers successfully for about 1 year.

    Better to post your topic in the developer community >  Developer Forums: Apple Support Communities

  • Having trouble printing an array of prime numbers that has been resized

    HI, im having trouble with my printPrimeNumbers() method printing the current state of an array, I can only get it to print the original state it was in. The array is inside of a primeNumbers object. I used checkAndResize to resize that array. my printPrimeNumbers method must be void without a parameter. How could i get my PrintPrimeNumbers method to print out a resized array without modifying the parameter? Any ideas.
    Here is my PrimeNumbers class:
    * Created by IntelliJ IDEA.
    * User: Kevin
    * Date: Mar 4, 2007
    * Time: 1:53:56 AM
    * To change this template use File | Settings | File Templates.
    package primes;
    public class PrimeNumbers {
        private boolean [] sieve;
        public PrimeNumbers(int  upper) {
            initializeSieve(upper);
        public int getNthPrime (int n){
        int prime = 0;
        double num;
        if (n >= sieve.length)
            checkAndResize(n + 1);
        for (int i = 0; i < sieve.length; i++){
            if(sieve)
    prime++;
    if (prime == n)
    return i;
    if (prime < n && i == sieve.length -1)
    checkAndResize(2*sieve.length);
    return -1;
    public int getNumberPrimeNumbers(int n){
    int primes = 0;
    for (int i =0 ; i < sieve.length ; i ++){
    if (n > sieve.length){
    checkAndResize(n);
    if(sieve[i])
    primes++;
    else if (sieve[i])
    primes++;
    return primes;
    public int getSieveSize ()
    return sieve.length;
    public boolean isPrime (int n) {
    if (n > sieve.length){
    checkAndResize(n);
    //initializeSieve(n);
    return sieve[n];
    // prints out the prime numbers inside sieve
    public void printPrimeNumbers() {
    int n = 0;
    boolean first = true;
    System.out.print("[");
    for(int i = 0; i < sieve.length - 1; i++){
    n++;
    if(sieve[i] == true && n != sieve.length - 1) {
    if(first) first = false;
    else System.out.print(" ");
    System.out.print(i);
    System.out.println("]");
    // checks length of sieve with N and then resizes sieve if nessecary.
    private void checkAndResize (int n){
    if ((n + 1) >= sieve.length){
    initializeSieve(2*n);
    private void setMultiples (int k) {
    for (int i = 2*k; i < sieve.length; i += k)
    sieve [i] = false;
    private void initializeSieve (int upper){
    if ( upper < 2)
    sieve = new boolean [2];
    else
    sieve = new boolean [upper + 1];
    sieve[0] = false;
    sieve[1] = false;
    for (int i =2 ; i< sieve.length; i ++ )
    sieve[i] = true;
    int bound = (int) Math.ceil(Math.sqrt(sieve.length));
    for (int i = 2 ; i < bound ; i ++)
    if (sieve[i])
    setMultiples (i);
    private String booleanToString (boolean value)
    if (value)
    return "T";
    else
    return "F";
    public String toString (){
    StringBuffer buf = new StringBuffer("[");
    for (int i = 0; i < sieve.length -1 ; i ++)
    buf.append(booleanToString (sieve[i]) + " " );
    buf.append(booleanToString (sieve[sieve.length -1]) + "]");
    return buf.toString();
    here is the client code
            PrimeNumbers test = new PrimeNumbers(16);
            System.out.println(test);
            System.out.println("There are " + test.getNumberPrimeNumbers(16) +
                    " prime nummbers in the sieve from 1 to 15. \n");
            System.out.println("There are " + test.getNumberPrimeNumbers(26) +
                    "  prime numbers in the resized sieve from 1 to 25.");
            System.out.println("\nThe first 25 prime numbers are:");// makes sense why it doesnt work
            test.printPrimeNumbers();
            System.out.println("\nThe 13th prime number is: " + test.getNthPrime(13));
            System.out.println();
            System.out.println("The number 3001 is prime:  " + test.isPrime(3001));do you see how my methods resized it?
    here is the output:
    [F F T T F T F T F F F T F T F F F]
    There are 6 prime nummbers in the sieve from 1 to 15.
    There are 15 prime numbers in the resized sieve from 1 to 25.
    The first 25 prime numbers are:
    [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47]// this is only the first 15 elements
    The 13th prime number is: 41
    The number 3001 is prime: true
    thanks for taking your time to look at this

    What's the problem?
    You say that there are 15 prime numbers in the range 1-25. Your method printPrimeNumbers() prints the last calculated primes, and that is 15. So the program works.

  • How can I get serial numbers or the free versions of Adobe, Air, Flash Player 14, and Reader XI Pro

    How can I get serial numbers or the free versions of Adobe, Air, Flash Player 14, and Reader XI Pro that I had installed on my computer before Microsoft crashed my computer and I had to do a fresh install? I finished reinstalling Win 8.1Pro on my computer thanks to Microsoft Lvl 1 Techies corrupting my Command Structure so nothing would work. I had recently taken a picture of my installed programs (control panel, uninstall programs list) so that I would be able to reinstall everything I needed. I can't seem to find an email for the Reader which I remember paying for, the others I believe were free installs. Can anyone help me out.

    Safari Version 5.0.5  <  from your first post
    5.0.5 is an outdated version of Safari.
    There is an update available for Safari for version 5.1.1
    That may help.
    Click your Apple menu icon top left in your screen the click Software Update
    Restart your Mac after the updates are installed.
    Try full screen ...
    If you have problems using Software Update from the menu you can use the standalone installer here >  Safari 5.1.1

  • HT201269 how do i get my numbers off my sim?

    AM TRYING TO GET MY NUMBERS OFF THE SIM IN MY IPHONE 4 PLEASE HELP NEW IPHONE USER

    If they are actually on sim here is the article to import the sim contacts http://support.apple.com/kb/HT4994
    That being said like dilbert41 said they are most likely not on there. If you have icloud just make sure contacts are turned on and as long as they did not come from like Facebook, work email, outlook etc they should merge into icloud. You can doublecheck by going to icloud.com , signing in and then clicking on the contacts to see what is in icloud. This means if they are all there then on the new phone all you have to do is use the same email when setting up the phone or signin to that icloud under settings > icloud in order to get the contacts.

  • Will Oracle pl/sql certification help me get  IT job

    Hello guys,
    I have completed my B.tech in Computer Science, I am confused a bit , Can i get a job after getting certified in Oracle Associate Pl/sql developer

    1005323 wrote:
    Hello guys,
    I have completed my B.tech in Computer Science, I am confused a bit , Can i get a job after getting certified in Oracle Associate Pl/sql developerYou may get a job after achieving Pl/sql developer OCA
    You may get a job after without achieving Pl/sql developer OCA
    You may fail to get a job after achieving Pl/sql developer OCA
    You may fail to get a job after without achieving Pl/sql developer OCA
    There are several factors involved in getting a job. And there are several ways a job may be obtained. But usually there are there stages:
    - Stage Zero: A company but has a job to offer.
    - And you need to be aware of it. - A friend may tell you, or an agency may tell you. And it must suit you for location and remuneration etc.
    - Stage one: An interview is obtained with the company.
    - Stage two: The job is offered to you rather than anyone else and you find it acceptable.
    So ... to your question:
    "Can i get a job after getting certified in Oracle Associate Pl/sql developer?"
    Well .... there is only three possible answers ... yes, no, and maybe; and maybe is probably the only correct answer, and most people will have worked this out, which means the question may have not been the best question to have asked.
    (( That said I now read the title of the thread and it says: Re: Will Oracle pl/sql certification help me get IT job)
    I have been known on occasion to have been given a question by a boss.
    And I have answered him:
    "You have given me the wrong question
    The question you should have answer me is this.
    And the answer I will give you is this."
    And the boss goes away happy
    So you you a better question would have been:
    How much will an OCA PL/SQL certification increase my chances of getting a job?
    Mind you even that question won't help you get a much better answer.
    For a proportion of jobs where PL/SQL is relevant that will help (for those where it is not it might be occasionally be a problem), for people with identical CV's it sometimes might help get to interview stage. But there are other factors as well. For instance if I was thinking of giving you a job on the basis of your post I might for example:
    - Not be impressed with an "Hello Guys" greeting ( though this is a forum so that isn't relevant here).
    - Not be impressed with you being confused.
    - etc.
    You probably need to get a good appreciation of the job market in your locality; and the numbers of applicants for each job. Which jobs you can apply for, what is your skillset and knowing youself as well.
    Sometimes an ITIL certification may be a better differentiator for some positions in business. But it will depend on the job you can think you can get.

  • Get Serial Numbers of a line item in a material document

    Hello everyone!
    My requirement goes like this:  For a material document, if a material code is serialized, I will also need to retrieve the corresponding serial numbers listed in the material document.  Is there a function module or table that I can use to connect the serial numbers to the material code?  If for example in matdoc 0001, material x1 the serial numbers are 1 and 2, then in matdoc 0002, material x2 the serial numbers are 3 amd 4. when I retrieve the details of matdoc 0001, I will only get serial numbers 1 and 2, not 1,2,3 and 4.
    Please help... points for any helpful answer.

    Hi, Check this Function module.
    SELECT_MATERIAL_SERIAL_NRS
    Regards,
    Maha

  • How to get serial numbers for materials in stock.

    Dear all,
    I need the table / FM from which i can get the serial numbers associated with a specific Material Doc Number.
    Currently, I am going to mseg-> get MBLNR
    Pass MSEG-MBLNR it to SER03 -> get Object List
    Pass SER03-OBKNR to OBJK -> get serial numbers( SERNR )
    As this is a long process and it will take time to execute , Please mention some alternatives by which we can get the desired result.
    Thanking you in advance,
    Shankar

    Hi Shankar;
       I am unaware of any function module, I searched for it high and low a few months ago...  This website describes the process of getting the serial numbers using WM if it is of any help to you...
    http://www.sapgenie.com/sapfunc/serialnumbers.htm
    Cheers,
    John

  • I have MacBook Pro Retina, but dint get pages, numbers and keynote for free with it, but others did. What to do?

    I have MacBook Pro Retina, but dint get pages, numbers and keynote for free with it, but others did. What to do?

    Solved the problem- I contacted apple on their support line found on this page... http://www.apple.com/uk/support/mac/ and they were really helpful and talked me through what to do on the phone, I now have all three productivity apps. Hope this helps

  • How can I calculate the Prime Numbers  ?

    Hi everyone ,
    I want to learn how can I do this :
    Write a Pl/SQL program using While loop , which will accept integer from 1 to 50 and generate the prime numbers as showen in the following output :
    The prime numbers from 1 to 50 are as follows :
    1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47

    HanyFreedom is one of the oracle's teachers that I have asked him yesterday about this Question .. I just know him via the internet ..
    now,
    I'm keep trying to find out what is the right answer..
    and this is my try :
    Declare
    counter number(10):=1;
    j number (4);
    begin
    DBMS_output.put_line('The prime numbers from 1 to 50 are as follows ');
    while counter < 50 loop
    FOR j in 2..50 loop
    if mod(counter,1)=0 and mod (counter,j)<>0 and mod(counter,2)<>0
    then
    dbms_output.put_line(counter);
    end if;
    counter:=counter+1;
    end loop;
    end loop;
    end;
    but there is something error because in the result i get number 49 which is not right
    Message was edited by:
    user635582

Maybe you are looking for

  • Creation of Control Problem: List of application EJB is empty

    Hello ! Could anybody assist me to solve this problem ? When I try to create EJB Control I can't receive list of application EJB. I'm receiving message no resources found in corresponding dialog for ejb's list. I can't understand what happened with a

  • Relative path of XSL in RTF

    Hello, I want to use common xsl file in RTF template. I will hardcode the path of the xsl file. Path should be relative path. Can anyone tell me how can I import xsl file into RTF template using relative path. e.g relative path may be BIP web cerver

  • HTMLLoader Breaks HTTP Attachments

    It seems that it is not possible to replicate standard browser behavior with Browser Attachments. If I go to any website that allows the downloading of a file to disk, an Air application can't be created such that it can save that HTTP attachment tha

  • UWL Iview getting 500 Internal Server Error

    Hi All, We have Uwl iview which is connected to R/3 system and its works fine. But if the user leaves the UWL session for more than 30 mins its get an message: " Web dynproapplicatie 'UWL' past. Start application again. Launch iView again via "Refres

  • Cannot determine sdm host

    Hi, I'm developiny webdynpro application usin NetWeaver Developer studio. While I deploy the error below appaers in log. How can I solve? Thanks. Sep 16, 2008 12:49:52 PM /userOut/deploy (com.sap.ide.eclipse.sdm.threading.DeployThreadManager) [Thread