How can I write a program in Blue J?
I want to do this:
x is in {0,1,2,...,9999}
Is x a prime? if not then give the the factors.
Is there natural numbers a,b such that x = a^3 + b^3 ?
I looked up BlueJ and found it's not a programming language, just an IDE.
There are many ways to get the factors of x in Java for x in that range. One is trial division, another is using a smallest prime sieve, and there are many others,
Integer factorization - Wikipedia, the free encyclopedia
Here is a simple way with trial division, it will be plenty fast for that range. You will probably learn more if you try coding yourself and only look at the code below as a last resort. There is some optimisation that might make it hard for you to read.
Spoiler:
I generally use a smallest prime sieve for larger numbers that aren't too large.
"Is there natural numbers a,b such that x = a^3 + b^3 ?"
This is a completely different question. However the answer is obviously yes since (a,b) = (1,1) satisfies.
Oh yeah the method above gives just the prime factors with multiplicity. I have other methods to turn this into a list of factors but you're probably better off just doing
The number is prime if and only if factors.size() == 2.Code:public ArrayList<Integer> getFactors(int n) { ArrayList<Integer> factors = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { if (n % i == 0) factors.add(i); } return factors; }
~~~~~~
Here's one way. Generate all cubes greater than 0 and less than 10^4. Put them in a list (sorted ascending). Then for each prime x, do a loop where you go through the list, subtracting the cube from x and seeing if the result is also in the list. Get out of the loop when the number you're subtracting is greater than floor(x/2).
For example you're going through all primes and you're currently at x = 23. Is 23-1=22 a perfect cube? No. Is 23-8=15 a perfect cube? No. And then you stop the loop because the next cube 27 is greater than floor(23/2). Thus 23 is not the sum of two cubes of natural numbers.
~~~~~~
Here's another way, probably a bit easier to write.
Do a loop within a loop:
Code:for(i=1,i3=1;i3+i3<9998;i++,i3=i*i*i) for(j=i,s=i3+j*j*j;s<9998;j++,s=i3+j*j*j) { // check if s is prime here }