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.

Similar Messages

  • Help creating an applet

    I need to create an applet from a standalone chat client.
    Can someone please help me, or suggest some good tutorials about writing applets?
    TIA,
    Richie.
    ------------------------BEGIN---------------------------
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class Client
    extends JPanel {
    public static void main(String[] args) throws IOException {
    String name = args[0];
    String host = args[1];
    int port = Integer.parseInt(args[2]);
    final Socket s = new Socket(host, port);
    final Client c = new Client(name, s);
    JFrame f = new JFrame("Client : " + name);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    c.shutDown();
    System.exit(0);
    f.setSize(300, 300);
    f.setLocation(100, 100);
    f.setContentPane(c);
    f.setVisible(true);
    private String mName;
    private JTextArea mOutputArea;
    private JTextField mInputField;
    private PrintWriter mOut;
    public Client(final String name, Socket s)
    throws IOException {
    mName = name;
    createUI();
    wireNetwork(s);
    wireEvents();
    public void shutDown() {
    mOut.println("");
    mOut.close();
    protected void createUI() {
    setLayout(new BorderLayout());
    mOutputArea = new JTextArea();
    mOutputArea.setLineWrap(true);
    mOutputArea.setEditable(false);
    add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
    mInputField = new JTextField(20);
    JPanel controls = new JPanel();
    controls.add(mInputField);
    add(controls, BorderLayout.SOUTH);
    mInputField.requestFocus();
    protected void wireNetwork(Socket s) throws IOException {
    mOut = new PrintWriter(s.getOutputStream(), true);
    final String eol = System.getProperty("line.separator");
    new Listener(s.getInputStream()) {
    public void processLine(String line) {
    mOutputArea.append(line + eol);
    mOutputArea.setCaretPosition(
    mOutputArea.getDocument().getLength());
    protected void wireEvents() {
    mInputField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String line = mInputField.getText();
    if (line.length() == 0) return;
    mOut.println(mName + " : " + line);
    mInputField.setText("");
    ------------------------------END------------------------------

    Thank you, that was very helpful info. I am new to java, so I find this exercise really touch. Here is what I have so far:
    -------------------------BEGIN-------------------------
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.applet.*;
    import javax.swing.*;
    public class Client extends Applet implements ActionListener {
         String name;
         String host;
         int port;
         final Socket s;
         final Client c;
         Button sendButton;
         TextField txtField;
         TextArea txtArea;
    public void init() {
              setLayout(new FlowLayout());
              name = "Richard";
              host = InetAddress.getLocalHost();
              port = 8000;
              Socket s = new Socket(host, port);
              Client c = new Client(name, s);
              txtField = new TextField();
              sendButton = new Button("Send");
              txtArea = new TextArea("Chat with " + name + " on " + host " : " + port);
              add(txtArea);
              add(txtField);
              add(sendButton);
         sendButton.addActionListener(this);
    public void paint(Graphics g) {
         g.setColor(Color.red);
         g.drawString("<" + name + "> " + txtField.getText(),20,250);
    public void actionPerformed(ActionEvent evt) {
    if (evt.getSource() == sendButton)
              repaint();
              txtArea.setText(txtField.getText());
    private String mName;
    private TextArea mOutputArea;
    private TextField mInputField;
    private PrintWriter mOut;
    public Client(final String name, Socket s)
    throws IOException {
    mName = name;
    createUI();
    wireNetwork(s);
    wireEvents();
    public void shutDown() {
    mOut.println("");
    mOut.close();
    protected void createUI() {
    setLayout(new BorderLayout());
    mOutputArea = new TextArea();
    mOutputArea.setLineWrap(true);
    mOutputArea.setEditable(false);
    add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
    mInputField = new TextField(20);
    JPanel controls = new JPanel();
    controls.add(mInputField);
    add(controls, BorderLayout.SOUTH);
    mInputField.requestFocus();
    protected void wireNetwork(Socket s) throws IOException {
    mOut = new PrintWriter(s.getOutputStream(), true);
    final String eol = System.getProperty("line.separator");
    new Listener(s.getInputStream()) {
    public void processLine(String line) {
    mOutputArea.append(line + eol);
    mOutputArea.setCaretPosition(
    mOutputArea.getDocument().getLength());
    protected void wireEvents() {
    mInputField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String line = mInputField.getText();
    if (line.length() == 0) return;
    mOut.println(mName + " : " + line);
    mInputField.setText("");

  • Need help creating movies in Snapz Pro and then editing them in FCE

    I'm in the process of creating a series of training videos on a software application that will ultimatley be on a DVD accompanying a book. I'm trying to use SnapZ Pro to capture the video (with audio) and then edit the sound in FCE. I have no clue what settings to use in Snap Z Pro for the best quality and that will be compatible with FCE. I tried a few samples and used the Animation codec (and various audio compressions). The audio tract was fine in FCE when I listened to it alone, but jumpy with lost segments when combined with the video. I'd appreciate some ideas of what settings to use at every step of the process for best results.
    When I tried saving a segment using the Apple Intermediate codec in Snapz Pro, FCE repeatedly crashed when importing the file.
    Any help would be greatly appreciated!
    Thanks!

    FCE is a fixed resolution video editing application. It will only work in DV or HDV. 10fps is not a frame rate used by either of those. The material needs to be in a standard frame resolution and frame rate. The standard for DV is 720x480 at 29.97fps. If you capture at 10fps you're going to have to save the material using the DV NSTC codec, set the frame size to 720x480 and the frame rate to 29.97. You may have pixel aspect ratio issues requiring capture at 720x540, but I don't know enough about SnapzPro to know how that product handles frame resolution and frame rate conversion.

  • Help creating browse sequences that work and deleting sync TOC

    Hi,
    I'm using the latest version of the TCS with RH 9.0. I'm trying to create WebHelp Pro output
    for a book produced originally in Framemaker. I've been following Rick's Skinny on skins
    guide to tailor the look and feel, but am having real problems getting my browse sequence
    to work. I've used Tools> Browse Sequence Editor and then Auto-create using Frame TOC,
    selected the TOC from the drop-down list and chosen 4  as the depth that I want to browse.
    The TOC that appears in Browse sequences  is strange and doesn't represent the Frame TOC that
    appears in the html, I left this 'as is'. Once I've generated the ouput the sequence browsing works
    for the equivalent of top-level heading only. What am I doing wrong and what should I
    be editing to make this fully functional?
    I would also like to delete the Sync TOC from the toolbar, and it seems to be possible to
    delete the image but not the entire field. I know it can be done, because Peter Grainge's
    RH site doesn't have it. Between Peter and Rick I will somehow achieve this website for
    my company...
    Many thanks in advance for any ideas and help.
    Best wishes,
    Karen

    Hi all
    @Jeff - In WebHelp output a Browse Sequence is presented using the arrows that sit in the Navigation Mini-Toolbar. I've documented some of it at the link below:
    Click here to view
    @Karen - Are you wanting one single sequence that works to allow the user to traverse the TOC from top to bottom or bottom to top? If so, the way you do this is by creating one very long sequence in the Browse Sequence Editor. You might begin by specifying 0 as the level to use when auto creating. Normally that will be sufficient. However, it depends on your TOC as to how well that may actually work.
    Cheers... Rick
    Helpful and Handy Links
    RoboHelp Wish Form/Bug Reporting Form
    Begin learning RoboHelp HTML 7, 8 or 9 within the day!
    Adobe Certified RoboHelp HTML Training
    SorcerStone Blog
    RoboHelp eBooks

  • HELP Creating Connections in the ABAP and JAVA Environments

    Hi good morning,
    I have a problem and I would like your help.
    I'm new at Abap and I'm trying to develop an application from ABAP to connect to an environment of java.
    I watched how to do this in various forums and the help of SAP, but just as I have found make the connection.
    In java I have already developed the server side and I have developed a ABAP function. But is not exactly how it works.
    Can you give me an example of how to send data from the sap application to java? Or give me any manual  please.
    Thank you very much in advance
    RAFA

    Hi Rajesh,
    You can not find no. of JCO connection fron ABAP Stack ......you have to login into JAVA Stack.
    <b>
    If useful ,Reward Points .</b>
    Thanks,
    Prashant.

  • Need some help with an applet

    I looked on the site here, read all the topics on it, and tried them all.
    but I can't get an applet to run on apex.
    I tried <applet> and <object> I get the same thing. the applet just does not work. I created the applet on jdeveloper and moved the .jar file into the static files area.
    I put the applet on apex.oracle.com at : http://apex.oracle.com/pls/apex/f?p=43533:1
    user id is guest, password is apex1234
    perhaps someone can look at this page and source code and tell me what I have done wrong? or maybe explain how to use the java console that pops up for details ?
    the applet works fine in jdeveloper.
    any help would be great..

    Looks like your code is trying to access http://apex.oracle.com/pls/apex/MyPack/MyCalc/class.class, whereas your applet is a workspace file (retrieved via wwv_flow_file_mgr.get_file). So essentially, code="..." and archive="..." arent following the same path conventions.
    &lt;applet name="MyCalc"
    code="MyPack/MyCalc.class"
    archive="wwv_flow_file_mgr.get_file?p_security_group_id=6032196320393432956&p_flow_id=43533&p_fname=MyCalc.jar"
    width="350"
    height="350"&gt;
    My applet works fine, and is located in XDB (I use EPG and it pretty much limits my file location options) in an open area, similar to /i/... (where Apex images, css etc are located), and so my code and archive locations are consistent.
    The applet could be hosted at any URL - it doesnt have to be in Apex.

  • 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]

  • 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

  • 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();
    }

  • I have tried for 2 days to create a calendar in Numbers and it keeps crashing...not sure what to do next

    I have tried for 2 days to create a calendar in Numbers and it keeps crashing on me.  I haven't had trouble before. I'm using Numbers version 3.5.2 on the latest OS...any help would be appreciated.
    Thanks so much!
    Tammy

    Hi Tammy,
    Please place a screen shot of where you are up to. Are you using formulas to calculate the next day's date? If so, what formulas?
    Here is a screen shot of a Year Planner in Numbers 3.
    Is this what you are trying to do?
    Regards,
    Ian.

  • I need help syncing my contacts between Outlook and iPhone using iTunes. I followed the steps given and ended up with just email addresses showing in my contacts even though I have phone numbers and snail mail in my Outlook Contacts. Using  Windows 7

    I need help syncing my contacts between Outlook and iPhone using iTunes. I used the knowldge document and set it up to transfer my Outlook contacts to the iphone using itunes.
    In contacts on the iphone I only see the email addresses.
    Yet in Outlook I have email, snail mail and phone numbers.
    I followed the knowledge document from iphone.
    I did it once, didn't work so deleted all the contacts from the phone and tried again. Same result. I have a PC using Windows 7 64 bit.

    You can't access an Exchange account via ActiveSync with the Address Book and iCal on your Mac.
    You can access a MM account with Outlook on your PC at work and keep your MM email account server stored mailboxes synced between your PC at work, your iPhone, and the MM "cloud". Not sure about syncing MM contact info and calendar events with Outlook at the same time with an Exchange account.
    This will not provide for syncing your Exchange account contact info and calendar events with the Addresss Book and iCal on your Mac because the accounts are separate.
    You can access an Exchange account and a MM account at the same time with the iPhone's mail client, and sync contact info and calendar events over the air with both accounts at the same time. You can view combined contact info or separately for each account, and the same for calendar events.

  • How can I exchange my pc created documents on Excel, Word, and PowerPoint with my mac and my Pages, Numbers and Keynote created content with my pc?  I need to create and edit between both.

    How can I exchange my pc created documents on Excel, Word, and PowerPoint with my mac and my Pages, Numbers and Keynote created content with my pc?  I need to create and edit and exchange between both types of operating systems.

    Your Windows system will not open any Pages, Numbers or Keynote documents. No applications exist for Windows that can open those formats. You will need to export your documents in Word, Excel and PowerPoint formats, respectively, before you'll be able to view and edit the documents on your Windows system. The iWork documents can natively open Word, Excel and PP documents, though there are limitations on what can be imported (for instance, Numbers does not support all possible Excel functions). Consult the documentation for the relevant iWork application for details on importing and exporting.
    If you are asking how to get the documents from one system to the other, then there are several ways to do that, including file sharing, using an external drive (hard drive, USB flash drive), or emailing the documents to yourself. Which would be best for your situation I can't say without more details about your usage.
    Regarsd.

  • Way to store and find the sum of prime numbers in a loop from 1 to an arbitrary N value

    i am intrested in a program in labview 8.5 to find out successive prime numbers between 1 to an arbitrary number N given as input and find out their sum as out put on front panel.
    Solved!
    Go to Solution.

    Is this a homework assignment?
    Spoiler (Highlight to read)
    Here's how I did it. 
    Here's how I did it. 
    Jim
    You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice

  • 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.

  • Can I create a template in numbers on my iPad

    My iPad and iPhone are my only apple devices, can I create a template in numbers using my iPad?

    Hello BoGodbold,
    Thanks for using Apple Support Communities.
    You will need to create a Numbers template on your Mac, and then transfer it to your iPad.
    You can create your own custom templates in Numbers for Mac and use them in Numbers on your iOS device. To install a custom template on your iOS device, first save your template to iCloud, iTunes, or a WebDAV server, or send it as an email attachment.
    Add custom templates
    http://help.apple.com/numbers/ipad/2.2/#/tan57e4f9f9c
    Take care,
    Alex H.

Maybe you are looking for