.
|
.
|
/****************************************
Matt is obsessed with math. He heard about Goldbach's
conjecture, which says that every even number can be
written as the sum of two prime numbers. For example:
100 = 11 + 89 . But it's difficult to find the primes
for a large number like a million. Matt wrote this program
that makes a list of prime numbers up to 1 million,
and then uses the list to solve Golbach for large numbers.
*****************************************/
public class Primes
{
int[] primes = new int[1000000]; // defaults to all zeroes
public Primes()
{
calculatePrimes();
int num = 0;
do
{
num = Integer.parseInt(input("Type a large even number"));
searchForPrimes(num);
} while(num != 0); // input 0 to end the program
}
void calculatePrimes() // sieve of Eratosthenes
{
primes[0] = 1;
primes[1] = 1;
for(int n = 2; n < 1000000; n = n+1)
{
int c = 2*n;
while(c < 1000000)
{
primes[c] = 1; // 1 indicates NOT prime
c=c+n;
}
}
}
void searchForPrimes(int num)
{
for(int x=3; x < num; x = x+2)
{
int p = num - x;
if( primes[x] == 0 && primes[p] == 0)
{
System.out.println(num + " = " + x + " + " + p);
}
}
}
public static void main(String[] args)
{ new Primes(); }
public String input(String prompt)
{ return javax.swing.JOptionPane.showInputDialog(null,prompt); }
public void output(String message)
{ javax.swing.JOptionPane.showMessageDialog(null,message); }
}
|
Computational Thinking is
about analyzing problems in such a way that they can be solved by a
computer system,
or at least a program can be written that will HELP to solve the
problem. Numerical problems were traditionally solved
with pencil and paper, using mathematical techniques like algebra and
calculus. But mastering mathematics is quite
difficult and most people have not learned mathematics in sufficient
depth that they can use it reliably to solve problems.
There are many theorems in
mathematics that might help, but most people are not aware of these
theorems,
or they simply don't understand them. And when we get to BIG
math problems, even good mathematicians
encounter their own limitations.
Prime numbers are relatively easy to understand. A prime number
is one that has no factors, nothing that divides
it evenly, except 1 and itself. For example, 83 is a prime number,
but 87 is not prime because 3 divides it.
It's not so bad when we work with numbers below 100. But what is
the largest prime number smaller than 1 million?
We can start counting backward:
999999 is divisible by 9
999998 is not prime because it's even
999997 is divisible by 757 - that's not so
obvious, but you can try it with a calculator
999995 is divisible by 5
999993 is divisible by 3 because the sum of the
digits is divisible by 3
999991 is divisible by 17
...