Generating primes.  i know the problem, just can't fix it.

I have to generate all the primes up to a given integer, but I'm failing horribly. I have to stay pretty close to what I've coded so far.
Here's the class I constructed
public class PrimeGenerator
     public PrimeGenerator()
     num=0;
     public PrimeGenerator(int num2)
     num=num2;
     public boolean isPrime()
     if (num==1)
          return false;
     if (num==2)
          return true;
     if ((num==3) || (num==5) || (num==7))
          return true;
     else if ((num%2==0) && (num%3==0) && (num%5==0) && (num%7==0))
          return false;
     return true;
     public int nextPrime()
     num++;
     while (!(isPrime()))
          num++;
     return num;
     private int num;
}Here's the test program I wrote to test it
import javax.swing.JOptionPane;
public class PrimeGeneratorTest
     public static void main(String[] args)
     String input=JOptionPane.showInputDialog("Enter a number");
     int limit = Integer.parseInt(input);
     PrimeGenerator prime=new PrimeGenerator(limit);
     int p = prime.nextPrime();
     while (limit>p)
          System.out.print(p + " ");
          p =prime.nextPrime();     
     System.exit(0);
}The only problem (I hope) is that the integer num of class PrimeGenerator is going to be set to that same as value as the object limit of the test, and the while loop in the test program is never executed. But everytime I change something in either program the result is just a different wrong answer. For example if I set num=0; in nextPrime(), then the while loop will execute in the program and it will be an endless loop displaying the number 2.
Actually its probably easier to look at the program than listen to me...but I really need to figure out how to correct this because its eating away at my soul.

Your main problem is, that your algorithm, that detects, wheter num is a prime number or not is wrong. Try to use another one (like the "Sieve of Eratosthenes"). Your PrimeGenerator class could then look something like this:
import java.util.ArrayList;
import java.util.Iterator;
public class PrimeGenerator{
  private int num;
  private ArrayList a;
  public PrimeGenerator() {
    num=1;
    a=new ArrayList();
  public boolean isPrime()  {
    Iterator iter = a.iterator();
    int i;
    while(iter.hasNext()) {
      i = ((Integer)iter.next()).intValue();
      if(num%i == 0) {
        return false;
    a.add(new Integer(num));
    return true;
  public int nextPrime()  {
    num++;
    while (!(isPrime())) num++;
    return num;
}Plus there is another problem with your test-class:
  PrimeGenerator prime=new PrimeGenerator(limit);Why do you set the num-field of the PrimeGenerator class to the limit you do not want to exceed in the testclass?

Similar Messages

  • My daughter disabled my iPhone (I know the ps) how can I fix it I don't have a computer at home just an iPad I don't what to loose my staff

    Please help me my daughter disabled my iPhone I know the ps how can I fix it I can't loose my staff

    See your other post, you need access to a computer. It can be a friend's computer. Disable sync when connected if using a friend's computer.
    Also see here: http://support.apple.com/kb/HT1212

  • I went in you tube and watched videos on how to fix my headphone jack and its not the headphones cause when I look inside I see this little white costing in there I think that's the problem how can I fix it

    I went in you tube and watched videos on how to fix my headphone jack and its not the headphones cause when I look inside I see this little white costing in there I think that's the problem how can I fix it

    - Try cleaning out/blowing out the headphone jack. Make sure that y do not leave any foreign material or leave anything in the jack. Try inserting/removing the plug a dozen times or so.
    Try the following to rule out a software problem
    - Reset the iPod. Nothing will be lost
    Reset iPod touch: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Reset all settings
    Go to Settings > General > Reset and tap Reset All Settings.
    All your preferences and settings are reset. Information (such as contacts and calendars) and media (such as songs and videos) aren’t affected.
    - Restore from backup
    - Restore to factory settings/new iPod.
    - Make an appointment at the Genius Bar of an Apple store. Seems you have a bad headphone jack.
    Apple Retail Store - Genius Bar
    If not under warranty Apple will exchange your iPod for a refurbished one for this price. They do not fix yours.
    Apple - iPod Repair price                  
    A third-party place like the following will replace the jack for less. Google for more.
    iPhone Repair, Service & Parts: iPod Touch, iPad, MacBook Pro Screens
    Replace the jack yourself
    iPod Touch Repair – iFixit

  • My 6180 has stopped printing the hp diagnostic tool says connectivity is the problem how can i fix

    how can i fix the c6180 that has stopped printing the hp diagnostic tool says connectivity is the problem

    Hi thefishermanfl,
    How is the printer connected to your computer?
    The following documents and utility should help you get the printer up and working again. Let me know if you need additional assistance.
    HP Print Diagnostic Utility:
    http://h10025.www1.hp.com/ewfrf/wc/softwareDownloadIndex?softwareitem=mp-91788-1&cc=us&dlc=en&lc=en&...
    Installing the Printer Software on a Wireless or Wired (Ethernet) Network:
    http://h10025.www1.hp.com/ewfrf/wc/document?docname=c02283715&tmp_task=useCategory&cc=us&dlc=en&jump...
    Installing the Product Software for a USB Cable Connection:
    http://h10025.www1.hp.com/ewfrf/wc/document?docname=c01793627&tmp_task=useCategory&cc=us&dlc=en&jump...
    I am an HP employee.
    Say Thanks by clicking the Kudos Star in the post that helped you.
    Please mark the post that solves your problem as "Accepted Solution"

  • My daughter disabled my phone but o know the pascode how can I fix it?

    Please help me because I use my phone for business purposes

    Force iPad into Recovery Mode. Follow step 1 to 6 very closely.
    http://support.apple.com/kb/HT1808
    Note: You may have to repeat the above a few times.

  • My iphone came up with that timing circle and just turned off and did not come back on ? even when i charge it now it still wont turn on ,do you know the problem?

    my iphone came up with that timing circle and just turned off and did not come back on ? even when i charge it now it still wont turn on ,do you know the problem?

    If the battery was empty (and it may then take 10 to 15 minutes of charging before it will respond), then have you tried a reset ? Press and hold both the sleep and home buttons for about 10 to 15 seconds, after which the Apple logo should appear - you won't lose any content, it's the equivalent of a reboot.

  • I can't upgrade my Mac to OS Mavericks. I still don't know the problem why. I have my mac with OS 10.8.5 and also a 2012 model . Please help me :((

    I can't upgrade my Mac to OS Mavericks. I still don't know the problem why. I have my mac with OS 10.8.5 and also a 2012 model >.< Please help me :((

    Oh that really works ;D Thanks

  • I know the iphone 4s can turn off the vibrate for all sounds, but is there a way to keep the vibration on for just phone calls (with the ringtone also on) but off for everything else?

    I know the iphone 4s can turn off the vibrate for all sounds, but is there a way to keep the vibration on for just phone calls (with the ringtone) but off for everything else?

    Short answer: No.  Long answer: Nope
    http://manuals.info.apple.com/en_US/iphone_user_guide.pdf
    WYSIWYG   No hidden settings.
    If you want to suggest this to Apple:
    http://www.apple.com/feedback/iphone.html
    Message was edited by: modular747

  • I restored my phone and some of my purchases can't download because they're from other account I don't know the passwords to, can I just download them from my computer?

    I restored my phone and some of my purchases can't download because they're from other account I don't know the passwords to, can I just download them from my computer?

    Apps are forever tied to the AppleID used to download them.
    You can download the missing apps under your own AppleID;
    if they are not free apps, you will have to pay for them.

  • Hi, I know the problem is in the movies & I need to download it too

    Hi, thanks for your help, but I know the problem is in the movies & I need to download it too,
    SO, what to do next to import all of them?
    AND, after I import it all at the Image Capture how can I move them to IPhoto.
    P.S: its my 1st time ever to be part of Apple Support Communities & share in it..its amaaaaazing

    Welcome to the Apple Support Communities!
    but I know the problem is in the movies & I need to download it too,
    Could you confirm your "image Capture" settings? How did you set the "Import to" pop-up?
    Make sure you import to a folder on your Desktop, and not into iPhoto.
    This way you can be sure, that no problem with the iPhoto library will interfere.
    Once you have the image files in a folder on the Desktop, test them by opening them and then import them to iPhoto.
    Is there a problem with posting answers for you? I notice, you keep creating new discussions for follow-up questions and answers. That makes it hard see all answers in context.
    If the "Reply" button is not working, close the Browser and sign in again. The software has a lot of problems right now.
    You other thread: Go to the message

  • HT201363 I forgot I made an apple id years ago. I dont know the password nor can I remember the password for the email address I used years ago. Can anyone help me authorize my music I bought with my super old id?

    I dont know the password nor can I remember the password for the email address I used years ago. Can anyone help me authorize my music I bought with my super old id?

    See this -> Find My iPhone Activation Lock: Removing a device from a previous owner’s account
    i just asked if someone knows the support mail, i don`t know how to someone from apple support
    -> AppleID Support - Contact Support
    Condolences to you and your family.

  • Why when I want to take photo , the camera will appear such pink colour vertical line and become black and the video just can record 1 min only  ?

    why when I want to take photo , the camera will appear such pink colour vertical line and become black and the video just can record 1 min only  ? why ? is that any problem ?

    are you using the iOS camera? if you do, visit your apple store for further help, sounds like a hardware problem.
    or:
    hold home and lock button pressed until your iphone restarts.
    if that didn't help, visit your apple store.
    if you are not using the iOS camera, delete that app.

  • Does anybody also know the problem of soundcutdown on facetime???

    does anybody also know the problem of sound cutdown while using facetime???

    Give us a chance to answer your first post!
    Now you have added the patch doesn't work for you, that
    wasn't in the other post. I haven't seen anyone report this for a
    long time so it would seem that later versions are OK, can't
    guarantee they will work for you.
    I don't know why the patch isn't working for you when it
    seems to have worked for most other people. If uninstalling the MS
    update is not an option, it would seem that forces you to try the
    upgraded version on a non production machine. Might be worth trying
    with a copy of your project deleting the RTF file so that RH
    recreates it from the DOC file.

  • Ipad is disabled connect to itune, my friend entered the wrong passcode , but i know my passcode how can i fixed it without loosing data

    my friend entered the wrong passcode , but i know my passcode how can i fixed it without loosing data

    How can I unlock my iPad if I forgot the passcode?
    http://www.everymac.com/systems/apple/ipad/ipad-troubleshooting-repair-faq/ipad- how-to-unlock-open-forgot-code-passcode-password-login.html
    iOS: Device disabled after entering wrong passcode
    http://support.apple.com/kb/ht1212
    How can I unlock my iPad if I forgot the passcode?
    http://tinyurl.com/7ndy8tb
    How to Reset a Forgotten Password for an iOS Device
    http://www.wikihow.com/Reset-a-Forgotten-Password-for-an-iOS-Device
    Using iPhone/iPad Recovery Mode
    http://ipod.about.com/od/iphonetroubleshooting/a/Iphone-Recovery-Mode.htm
    You may have to do this several times.
    Saw this solution on another post about an iPad in a school environment. Might work on your iPad so you won't lose everything.
    ~~~~~~~~~~~~~
    ‘iPad is disabled’ fix without resetting using iTunes
    Today I met my match with an iPad that had a passcode entered too many times, resulting in it displaying the message ‘iPad is disabled – Connect to iTunes’. This was a student iPad and since they use Notability for most of their work there was a chance that her files were not all backed up to the cloud. I really wanted to just re-activate the iPad instead of totally resetting it back to our default image.
    I reached out to my PLN on Twitter and had some help from a few people through retweets and a couple of clarification tweets. I love that so many are willing to help out so quickly. Through this I also learned that I look like Lt. Riker from Star Trek (thanks @FillineMachine).
    Through some trial and error (and a little sheer luck), I was able to reactivate the iPad without loosing any data. Note, this will only work on the computer it last synced with. Here’s how:
    1. Configurator is useless in reactivating a locked iPad. You will only be able to completely reformat the iPad using Configurator. If that’s ok with you, go for it – otherwise don’t waste your time trying to figure it out.
    2. Open iTunes with the iPad disconnected.
    3. Connect the iPad to the computer and wait for it to show up in the devices section in iTunes.
    4. Click on the iPad name when it appears and you will be given the option to restore a backup or setup as a new iPad (since it is locked).
    5. Click ‘Setup as new iPad’ and then click restore.
    6. The iPad will start backing up before it does the full restore and sync. CANCEL THE BACKUP IMMEDIATELY. You do this by clicking the small x in the status window in iTunes.
    7. When the backup cancels, it immediately starts syncing – cancel this as well using the same small x in the iTunes status window.
    8. The first stage in the restore process unlocks the iPad, you are basically just canceling out the restore process as soon as it reactivates the iPad.
    If done correctly, you will experience no data loss and the result will be a reactivated iPad. I have now tried this with about 5 iPads that were locked identically by students and each time it worked like a charm.
    ~~~~~~~~~~~~~
    Try it and good luck. You have nothing more to lose if it doesn't work for you.
     Cheers, Tom

  • IMac screen has been flickering, does anyone know the problem?, iMac screen has been flickering, does anyone know the problem?

    Recently my iMac screen has started to flickering does anyone know the problem?
    Any help appreciated

    Bad power, unshielded speakers, improper hardware installs which lead to loose cables, can all cause this.

Maybe you are looking for

  • How do i change the font in preview pane in Mail?

    how do i change the font in preview pane in Mail?

  • "ipod nano cases"

    These cases for the new ipod nano ROCK! http://www.speckproducts.com/for-nano.html http://playlistmag.com/features/2005/10/04/nanocases/index.php

  • SQL Execution Error in Eclipse 3.5 (Windows Vista)

    Selecting and executing this query in SQL Scrapbook in Eclipse 3.5 produces "Failed" status. If I remove commented fields then it works OK. Using the latest OEPE Patch Set 1. SELECT * FROM (SELECT 'Patient' AS USERTYPE, SUM(TOTAL) AS Total FROM( SELE

  • Sap Query Link Tables

    Hi, I badly need your help.. How can I link Table LIPS to VBEP using SAP QUERY? I have join these two tables using key field VGBEL = VBELN and VGPOS=POSNR but database access takes too long.. I need to get Schedule line delivery date(VBEP- EDATU ) wh

  • Connecting to an Oracle 8i Database

    Hi Everyone, Has there been any successful ODI 11g connection (via Studio or Agent) to an Oracle 8i database? When I create a new Data Server, and select the Oracle JDBC driver in the list, I get this prompt message: Oracle JDBC Driver (Type 4 / Type