Why do large numbers throw error?

  • (2 Pages)
  • +
  • 1
  • 2

27 Replies - 1022 Views - Last Post: 17 May 2012 - 12:01 PM Rate Topic: -----

#1 GilkeAnthony  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 20
  • Joined: 14-May 12

Why do large numbers throw error?

Posted 14 May 2012 - 03:37 PM

This is the error I get:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "1111111111111"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at GUIPackage.MyForm$4.actionPerformed(MyForm.java:138)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)



Seems like big numbers give the error. Such as 32416188899 throw the error. Smaller numbers such as 10000 work fine.

package BusinessLogicPackage;

import java.math.BigInteger;

/**
 * PrimeNumbers class
*/
public class PrimeNumbers{

	/**
	 * isPrime method
	 * @param num The number to be checked
	 * @return true if int is prime
	 */
	public static boolean isPrime(int num) {
		// set status to true
		boolean status = true;
		// ToDo: Write this logic
		int i = 2;
		while (i < num) {
			// If number is not prime return false
			if ((num % i) == 0) {return false;}
			i++;
		}
		// Return true if prime
		return status;
		
	}
	
	/*
	 * BigintisPrime Method
	 * @ Return boolean 
	 */
	public static boolean BigIntisPrime(BigInteger B)/> {

			BigInteger i = new BigInteger("2");	
			while (i.compareTo(B)/> < 0){
				BigInteger tmp = b.mod(i);
				if(tmp.compareTo(BigInteger.ZERO) == 0) {
					//System.out.println("Factor Found: " + i.toString()); 
					return false;}
				i = i.add(BigInteger.ONE);
			}
			
			return true;	
			
		}	
}



HERE IS MY FORM Class

import java.awt.Color;

/**
 * MyForm JFrame
 */
public class MyForm extends JFrame {

	// Declarations
	private JPanel contentPane;
	private final JLabel lblEnterANumber = new JLabel("Enter a Number:");
	private final JTextField textField = new JTextField();
	private final JLabel lblTrueOrFalse = new JLabel();
	private final JButton btnExit = new JButton("Exit");
	private final JButton btnCompute = new JButton("Compute");
	private boolean prime;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MyForm frame = new MyForm();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MyForm() {
		setTitle("Find the Prime-Ness!");
		// MouseListener to erase text in input box when clicked
		textField.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				// When clicked set text field to null
				textField.setText(null);
			}
		});
		// Set size for textField
		textField.setBounds(10, 26, 138, 20);
		textField.setColumns(10);
		// Close JFRAME when exited
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// Set size of JFrame
		setBounds(100, 100, 424, 248);
		contentPane = new JPanel();
		// set border
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		// set color
		contentPane.setBackground(Color.green);
		setContentPane(contentPane);
		contentPane.setLayout(null);

		// Add label for enter a number and set size
		contentPane.add(lblEnterANumber);

		// Set size & position of label
		lblEnterANumber.setBounds(10, 11, 102, 14);

		// Create text field and set size
		contentPane.add(textField);

		// Set size & position of label
		lblTrueOrFalse.setBounds(10, 142, 388, 14);

		// Create answer label and Set to false  
		contentPane.add(lblTrueOrFalse);

		// Set label to hide
		lblTrueOrFalse.setVisible(false);

		// Exit button action 
		btnExit.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				// Exit program
				System.exit(0);
			}
		});

		// Set exit button size
		btnExit.setBounds(309, 176, 89, 23);

		// Add exit button
		contentPane.add(btnExit);

		/*
		 * This action listener will perform different actions based on what is entered 
		 * If negative number: on button press the listener will post warning label
		 * If positive number: on button press the listener will post message and compute number to find primeness
		 */
		// Create actionlistener for Compute button
		btnCompute.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				// Set primeValue to what is entered in textField/ set to string
				String primeValue = textField.getText();

				// parse the string to an integer
				int num = Integer.parseInt(primeValue);
				
				// If the number is less than 0 set label to tell user to enter positive number
				if ((num < 0) || (num > 10000)){
					// Set label to true
					lblTrueOrFalse.setVisible(true);
					// Print label if number is negative
					lblTrueOrFalse.setText("Please enter number greater than 0");
					//System.exit(0);

				// If positive number continue to find primeness
				}else {
					// Set to BigInteger				
					BigInteger myBig = new BigInteger(primeValue);

					// Assign prime to isPrime num
					prime = PrimeNumbers.BigIntisPrime(myBig);								

					// If prime print following
					if (prime){
						// If prime set label to is prime
						lblTrueOrFalse.setText("The Number " + primeValue + " is prime-ness");
					}

					// Else print following
					else {
						// If not prime set label to is not prime
						lblTrueOrFalse.setText("The Number " + primeValue + " does not have prime-ness");	
					}
					// Make label visible
					lblTrueOrFalse.setVisible(true);
				}
			}
		});
		// Set size of button
		btnCompute.setBounds(156, 92, 89, 23);
		// Add button
		contentPane.add(btnCompute);
	}
}



Is This A Good Question/Topic? 0
  • +

Replies To: Why do large numbers throw error?

#2 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 1500
  • View blog
  • Posts: 3,211
  • Joined: 11-December 07

Re: Why do large numbers throw error?

Posted 14 May 2012 - 03:43 PM

It's because the maximum value for an int is 2,147,483,647. If you need larger numbers, use long or BigInteger. More info here:

http://docs.oracle.c.../datatypes.html
Was This Post Helpful? 2
  • +
  • -

#3 GilkeAnthony  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 20
  • Joined: 14-May 12

Re: Why do large numbers throw error?

Posted 14 May 2012 - 03:45 PM

View Postcfoley, on 14 May 2012 - 03:43 PM, said:

It's because the maximum value for an int is 2,147,483,647. If you need larger numbers, use long or BigInteger. More info here:

http://docs.oracle.c.../datatypes.html


I'm comparing the number using my bigIntisPrime class. Is that not enough?

View Postcfoley, on 14 May 2012 - 03:43 PM, said:

It's because the maximum value for an int is 2,147,483,647. If you need larger numbers, use long or BigInteger. More info here:

http://docs.oracle.c.../datatypes.html


I'm comparing the number using my bigIntisPrime class. Is that not enough?
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8016
  • View blog
  • Posts: 31,118
  • Joined: 06-March 08

Re: Why do large numbers throw error?

Posted 14 May 2012 - 03:57 PM

You only use BigInteger in that method so the error is not coming from there
Was This Post Helpful? 0
  • +
  • -

#5 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2110
  • View blog
  • Posts: 8,774
  • Joined: 20-September 08

Re: Why do large numbers throw error?

Posted 14 May 2012 - 03:58 PM

Quote

I'm comparing the number using my bigIntisPrime class. Is that not enough?


It's not happening there. It's happening where you're entering too large a number for int into the gui and then calling parseInt on it
Was This Post Helpful? 1
  • +
  • -

#6 GilkeAnthony  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 20
  • Joined: 14-May 12

Re: Why do large numbers throw error?

Posted 14 May 2012 - 03:59 PM

View Postcfoley, on 14 May 2012 - 03:43 PM, said:

It's because the maximum value for an int is 2,147,483,647. If you need larger numbers, use long or BigInteger. More info here:

http://docs.oracle.c.../datatypes.html


I use long and it locks it up!
Was This Post Helpful? 0
  • +
  • -

#7 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2110
  • View blog
  • Posts: 8,774
  • Joined: 20-September 08

Re: Why do large numbers throw error?

Posted 14 May 2012 - 04:03 PM

Finding primes is a tough business (luckily or we wouldn't have strong encryption) - you need to be patient (assuming no errors) ;)

This post has been edited by g00se: 14 May 2012 - 04:04 PM

Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8016
  • View blog
  • Posts: 31,118
  • Joined: 06-March 08

Re: Why do large numbers throw error?

Posted 14 May 2012 - 04:04 PM

long num = Long.parseLong(primeValue);

Will give you 2^32 more
But as you use BigInteger better read as a String a build a BigInteger out of it
Was This Post Helpful? 1
  • +
  • -

#9 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 1500
  • View blog
  • Posts: 3,211
  • Joined: 11-December 07

Re: Why do large numbers throw error?

Posted 14 May 2012 - 04:06 PM

	/**
	 * isPrime method
	 * @param num The number to be checked
	 * @return true if int is prime
	 */
	public static boolean isPrime(int num) {
		// set status to true
		boolean status = true;
		// ToDo: Write this logic
		int i = 2;
		while (i < num) {
			// If number is not prime return false
			if ((num % i) == 0) {return false;}
			i++;
		}
		// Return true if prime
		return status;
		
	}



Probably because this will be extremely slow for very large numbers. You can test this (and watch the progress) by adding a line like this into the loop:

if (i % 10000 == 0) System.out.println(i + ": " + (int)((double)i / num * 100) + "%");

If I'm right, you might want to limit the user to a sensible range of numbers or look into more efficient methods like the sieve of eratosthenes.
Was This Post Helpful? 0
  • +
  • -

#10 GilkeAnthony  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 20
  • Joined: 14-May 12

Re: Why do large numbers throw error?

Posted 14 May 2012 - 04:12 PM

View Postg00se, on 14 May 2012 - 04:03 PM, said:

Finding primes is a tough business (luckily or we wouldn't have strong encryption) - you need to be patient (assuming no errors) ;)



Been running for 15 minutes as a long. Won't throw an error, just hangs. Hmmmmmmmmmmmm
Was This Post Helpful? 0
  • +
  • -

#11 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2110
  • View blog
  • Posts: 8,774
  • Joined: 20-September 08

Re: Why do large numbers throw error?

Posted 14 May 2012 - 04:14 PM

Optimisation would be a good idea, per cfoley's suggestion. I didn't even notice you were not using the Sieve, but even if you do, you can expect it to tax your processing resources

This post has been edited by g00se: 14 May 2012 - 04:15 PM

Was This Post Helpful? 0
  • +
  • -

#12 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 1500
  • View blog
  • Posts: 3,211
  • Joined: 11-December 07

Re: Why do large numbers throw error?

Posted 14 May 2012 - 04:58 PM

At least stick in the line that prints out i every so often, just so you can see why it takes so long.
Was This Post Helpful? 0
  • +
  • -

#13 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 9025
  • View blog
  • Posts: 33,463
  • Joined: 27-December 08

Re: Why do large numbers throw error?

Posted 14 May 2012 - 05:03 PM

@cfoley: You actually only need to check up to the sqrt(n). A little more optimization: :)
public boolean isPrime(int x){
   
    //2 is the first prime
    if(x == 2){ return true; }

    //other evens are not primes
    else if(x%2 == 0){ return false;}

    double sqrt = Math.sqrt(x);

    //check up to the sqrt(x), ignoring other evens
    for(int i = 3; i <= sqrt; i += 2){

        if(x%i == 0 && x != i){ return false; }
    }

    return true;
}



The BigInteger isProbablePrime() method is also helpful, though certainly not perfect for substantially larger numbers.

This post has been edited by macosxnerd101: 14 May 2012 - 05:11 PM
Reason for edit:: Added extra optimization as pointed out by pbl

Was This Post Helpful? 0
  • +
  • -

#14 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8016
  • View blog
  • Posts: 31,118
  • Joined: 06-March 08

Re: Why do large numbers throw error?

Posted 14 May 2012 - 05:06 PM


 while (i < num) {
        // If number is not prime return false
        if ((num % i) == 0) {return false;}
        i++;
    }



Kind of useless to check for all even number
Check for % 2
then start with i = 3
and do i += 2; you just cut by two the number of iterations in your loop

no need to test up to num.. of to sqrt(num) will do it

for(int i = 3; i <= Math.sqrt(x); i += 2){

don't call sqrt() at each iteration of your loop. Do it only once before starting the loop
Was This Post Helpful? 2
  • +
  • -

#15 GilkeAnthony  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 20
  • Joined: 14-May 12

Re: Why do large numbers throw error?

Posted 15 May 2012 - 05:28 AM

View Postpbl, on 14 May 2012 - 05:06 PM, said:


 while (i < num) {
        // If number is not prime return false
        if ((num % i) == 0) {return false;}
        i++;
    }



Kind of useless to check for all even number
Check for % 2
then start with i = 3
and do i += 2; you just cut by two the number of iterations in your loop

no need to test up to num.. of to sqrt(num) will do it

for(int i = 3; i <= Math.sqrt(x); i += 2){

don't call sqrt() at each iteration of your loop. Do it only once before starting the loop



The isPrime method is there from other programs. I'm using the BigIntisPrime method. Thanks.

	public static boolean BigIntisPrime(BigInteger B)/> {

			BigInteger i = new BigInteger("2");	
			while (i.compareTo(B)/> < 0){
				BigInteger tmp = b.mod(i);
				if(tmp.compareTo(BigInteger.ZERO) == 0) {
					System.out.println("Factor Found: " + i.toString()); 
					return false;}
				i = i.add(BigInteger.ONE);
			}
			
			return true;	
			
		}	


Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2