Welcome to Dream.In.Code
Become a Java Expert!

Join 150,196 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 2,032 people online right now. Registration is fast and FREE... Join Now!




Help with prime and composite numbers

 
Reply to this topicStart new topic

Help with prime and composite numbers

Sucklefish
18 Sep, 2008 - 04:16 PM
Post #1

New D.I.C Head
*

Joined: 23 Aug, 2008
Posts: 6

So I have a way to determine of a number is prime or composite and it works fine but its not exactly the best code...

java
double[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};


java
for (int scan = 0; scan < primeNums.length; scan++) // scans array of primeNums[]
{
if (d == primeNums[scan]) prime = "Prime"; // if it finds a prime
else prime = "Composite"; // if it doesnt find a prime
if ( ( d % 2 ) != 0) prime = "Prime"; // if the number is a decimal


I need something that can determine if it is prime or composite with out listing them out.

my brain is so fried right now I have no idea where to even start. ANY help would be greatly appreciated.

Also If anyone has a good tut for getting rid of one giant public into smaller privates I also have no idea how to do that

This post has been edited by Sucklefish: 18 Sep, 2008 - 04:17 PM
User is offlineProfile CardPM
+Quote Post

pbl
RE: Help With Prime And Composite Numbers
18 Sep, 2008 - 04:39 PM
Post #2

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,587



Thanked: 233 times
Dream Kudos: 75
My Contributions
There are dozen of algorithms to compute prime numbers. If you search this foreum for "prime number" you will find multiple implementations.

In your case a quick dirty trick would do it.... (by the way you declare your primes as double, they should be int) but I will use a boolean

CODE

boolean[] isPrime = new boolean[10000];    // init first 10000 at false

for(i  = 1; i < isPrime.length; i += 2)    // put all the odd one to true
   isPrime[i] = true;

for(int i = 3; i < isPrime.length; i += 2 {    // no need to test the even one
   for(j = 3; j < i; j += 2) {
       if(i % j == 0) {
            isPrime[i] = false;
            break;
       }
   }
}



User is offlineProfile CardPM
+Quote Post

BetaWar
RE: Help With Prime And Composite Numbers
18 Sep, 2008 - 04:54 PM
Post #3

#include <soul.h>
Group Icon

Joined: 7 Sep, 2006
Posts: 2,304



Thanked: 101 times
Dream Kudos: 1275
My Contributions
Here is a quick app that will find if a number is prime, and if it isn't what all the components that create the number are:
CODE
import java.util.Scanner;

public class PrimeFinder{
    private static String comps;
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Please insert a number:");
        int number = input.nextInt();
        comps = "";
        boolean prime = isPrime(number);
        if(prime){
            System.out.println("The number "+number+" is Prime");
        }
        else{
            System.out.println("The number "+number+" is composed of "+comps);
        }
    }
    public static boolean isPrime(int num){
        boolean isTrue = true;
        for(int i=2; i<=Math.ceil((num/2)); i++){
            if(num%i == 0){
                if(comps.equals("")){
                    comps += ""+i;
                }
                else{
                    comps += ","+i;
                }
                isTrue = false;
            }
        }
        return isTrue;
    }
}


If you wanted to find out what half of the components are you could say
CODE
import java.util.Scanner;

public class PrimeFinder{
    private static String comps;
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Please insert a number:");
        int number = input.nextInt();
        comps = "";
        boolean prime = isPrime(number);
        if(prime){
            System.out.println("The number "+number+" is Prime");
        }
        else{
            System.out.println("The number "+number+" is composed of "+comps);
        }
    }
    public static boolean isPrime(int num){
        boolean isTrue = true;
        for(int i=2; i<=Math.ceil(Math.sqrt(num)); i++){
            if(num%i == 0){
                if(comps.equals("")){
                    comps += ""+i;
                }
                else{
                    comps += ","+i;
                }
                isTrue = false;
            }
        }
        return isTrue;
    }
}


Instead. NOTICE - it uses the square root function instead of dividing by 2.

Hope that helps.
User is offlineProfile CardPM
+Quote Post

Sucklefish
RE: Help With Prime And Composite Numbers
18 Sep, 2008 - 06:55 PM
Post #4

New D.I.C Head
*

Joined: 23 Aug, 2008
Posts: 6

Well I basically feel like a complete idiot right now. I tried both of your examples trying to adapt it to my code but my head is just not clear right now.

java
/**
* @(#)numbergame.java
*
* numbergame application
*
* @Kevin Ryan
* @version 1.00 2008/9/5
*/
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.String;
public class numbergame
{
public static void main(String[] args)
{
int play, error = 0, playagain; // declares play and error which prompt the start box and whether or not there were errors
double[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
String s2 = "0", s = "0", even = "", prime = ""; // declares strings for prime, even, and the input string before and after trim
double d = 0 , squareroot, squared; // declares double for d which is the value holder, squareroot, and squared.

play = JOptionPane.showConfirmDialog (null,"Would you like to play a game?"); // prompts to start game
if (play == JOptionPane.YES_OPTION) // if the user presses yes
if (play == JOptionPane.CANCEL_OPTION)
System.exit(0);
if (play == JOptionPane.NO_OPTION)
System.exit(0);
do{
{
s = JOptionPane.showInputDialog ("Enter a number between 1 and 100\nand click ok"); // input box
s2 = s.trim(); // trims answer
}

try {
d = Double.parseDouble(s2); // tries to parse into a double
}
catch(NumberFormatException ex) // if it can't parse it
{
error = 1; // throws an error
JOptionPane.showMessageDialog(null, "You entered an invalid value.\nSystem Critical!\nShuting down...", "!!!", JOptionPane.ERROR_MESSAGE); // tells them they entered an invalid value
if (error == 1) System.exit(0); // closes program if errors == 1
}
if (d < 0 || d > 100) JOptionPane.showMessageDialog(null, "You entered a value that is out of range.\nSystem Critical!\nShuting down...", "!!!", JOptionPane.ERROR_MESSAGE); // if the number is too big
if (d < 0 || d > 100) System.exit(0); // if the number is too big
if ( ( d % 2 ) == 0) even = "even"; // if its even
if ( ( d % 2 ) != 0) even = "odd"; // if its odd

for (int scan = 0; scan < primeNums.length; scan++) // scans array of primeNums[]
{
if (d == primeNums[scan]) prime = "Prime"; // if it finds a prime
else if (d != primeNums[scan]) prime = "Composite"; // if it doesnt find a prime
}

squareroot = Math.sqrt(d); // gets the squareroot
squared = d * d; // squares it
// Displays output.
if (d >= 0 || d <= 100) JOptionPane.showMessageDialog(null, "You entered: " + d + "\n" + d + " is " + even + "\nThe squareroot of " + d + " is: " + squareroot + "\nThe square of " + d + " is " + squared + "\nThat number is a " + prime + " number");
playagain = JOptionPane.showConfirmDialog(null, "Would you like to play again?");
}
while (playagain == JOptionPane.YES_OPTION);

}
}



I realized that the code i had
CODE
if ( ( d % 2 ) != 0) prime = "Prime"; // if the number is a decimal

was taking out all odd numbers, not sure how i didn't catch that before.

I'm not even sure as to what to do at this point. I can't turn it in as is considering it doesn't even work at all now.

Gah I hate getting this frustrated it makes it even more impossible to think
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/9/09 04:43AM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month