# From python to java

• January 11th, 2012, 05:01 PM
JeremiahWalker
From python to java
This is a program to generate all prime numbers between 0 and a given number(y). Is it possible to "translate" this program to java? The assignment calls on me to do this in java and I see no need to reinvent the wheel.

Code :

```#Function that determines whether a number is prime def Primality(n): if n < 2: return False for x in range (2, int(math.sqrt(n)) + 1): if n % x == 0: return False return True   # variables to keep track of primes found and to advance the number tested primes = 0 # counts the number of prime numbers the program finds n = 1 # variable used by the program to count and run each number through the primality function y = 10000 # the limit for the counter.   # while loop calls the primality function until "y" primes are found. It will also list the prime numbers found while primes < y: n += 1 Primality(n) if Primality(n): print( n ) primes += 1   print( "I have", primes ,"prime numbers" ) print( n, "is the nth prime number.")```
• January 11th, 2012, 05:24 PM
pbrockway2
Re: From python to java
It's worth keeping an open mind about the purpose of the assignment. It is just possible that whoever assigned it is genuinely in need of knowing the first thousand primes and believes this to be an "outstanding" problem in number theory which requires some novel algorithm. An alternative is that the whole point of it is for you to "reinvent the wheel": that is there is some value to be had in going through the process of implementing a straight forward algorithm with correct Java code.

The simple answer to your question is that it is quite possible to translate this program into Java. But consider whether you want to do things this way. It will involve understanding Python syntax as well as Java. And you are putting some faith in the fact that it's good prime finding code (it isn't).

Even without understanding the details of Python you should be able to see roughly how that code goes about things and that may give you a starting point as you do the assignment and write the Java code.

Good luck, and ask any questions if they arise.
• January 11th, 2012, 06:55 PM
JeremiahWalker
Re: From python to java
good point. I actually wrote that program when I was first starting out in programming.
• January 11th, 2012, 07:38 PM
pbrockway2
Re: From python to java
Good, so that makes writing the Java version that much easier. (Just don't include the redundant primality check.)

But - unless someone cares to do your assignment for you - we really need to see your translation of the code, and the question you have about it.
• January 11th, 2012, 09:49 PM
JeremiahWalker
Re: From python to java
Here is one using the Sieve of Eratosthenes. I found the algorithm on wikipedia.
I'm going to translate it to python

Code :

```//Jeremiah A. Walker //Prime number generator //Java //Sieve of Eratosthenes /* The sieve of Eratosthenes is an algorithm we can use for rapidly locating all the prime numbers within a range of integers. It works by marking all nontrivial multiples of each prime in sequence until only primes remain unmarked. It is most well-suited to implementation using arrays, which are compact and feature random access. */   import java.util.*; //java.util.Bitset gives a vector of bits that grows as needed.   public class Sieve { /* K is used to indicate the primality of a number 2k + 3. This is done to save time. BitSet goes into a class to expose some indexer methods. */ private BitSet sieve;   public Sieve(int size) { sieve = new BitSet((size+1)/2); }//end Sieve   public boolean is_composite(int k) { assert k >= 3 && (k % 2) == 1; return sieve.get((k-3)/2); }//end is_composite   public void set_composite(int k) { assert k >= 3 && (k % 2) == 1; sieve.set((k - 3)/2); }//end set_composite   public static List<Integer> SieveOfEratosthenes(int max) {     /* The sieve begins by creating the sieve array and then searching for the first zero entry. All odd multiples of i are set to true to indicate that they are composit. We start with i-squared because all multiples of i smaller than that are already set to composite. By default, a BitSet is initialized to all zeroes, as is required by the algorithm */     Sieve sieve = new Sieve(max + 1); //+1 to include max itself   for(int i = 3; i*i <= max; i += 2) { if(sieve.is_composite(i)) continue;   //we will increment by 2i to skip even multiples of i for(int multiple_i = i*i; multiple_i <= max; multiple_i += 2*i) sieve.set_composite(multiple_i); }//end for     /*When we're done, we iterate through the sieve, forming an ArrayList of elements that are not composite(IE the numbers that are prime prime) Which returns our prime numbers*/       List<Integer> primes = new ArrayList<Integer>(); primes.add(2); for(int i = 3; i <= max; i += 2) if(!sieve.is_composite(i))//if the number is not composite, add to the primes primes.add(i); return primes; }//end Sieve of Eratosthenes       /*Here is the tester. We take a limit value(max), determine the time it took for the computation, and write a list of our primes. */         public static void main(String[] args) {   Scanner input = new Scanner(System.in); System.out.println("Enter a number and I will give you all the primes between zero and that number: "); int max = input.nextInt(); int num_times = 1;     if (args.length > 0) max = Integer.parseInt(args[0]);   if(args.length > 1) num_times = Integer.parseInt(args[1]);   List<Integer> result = null; long start_time = System.currentTimeMillis(); for(int i = 0; i < num_times; i++) result = SieveOfEratosthenes(max);     double TimeInMs = (double)(System.currentTimeMillis() - start_time) / num_times; double time_per_integer_ns = TimeInMs / max * 1000000;   System.out.print("Sieved over integers 1 to " + max + " in " + TimeInMs + "ms (" + time_per_integer_ns + " ns per integer)\n");   for(Integer i : result) System.out.println(i);     System.out.print("Sieved over integers 1 to " + max + " in " + TimeInMs + "ms (" + time_per_integer_ns + " ns per integer)\n\n");   }//end main }//end class Sieve```
• January 11th, 2012, 10:09 PM
JeremiahWalker
Re: From python to java
Is it possible to reach in to the primes array and grab primes[max] to be able to print the "nth" prime number
• January 11th, 2012, 11:16 PM
helloworld922
Re: From python to java
Not directly. The output from the sieve of eratosthenes only tells you if a number in the given range is prime or not. You can go through the entire range of numbers again and harvest out all numbers that are prime into a list, though.

edit:

nvm, it looks like the sieve code you posted already does that. I would say, though, since this is an assignment the purpose is likely not to pull code someone else has written. More likely, it's to help yourself come up with a solution on your own with minimal outside help. There is great value in a programmer who can think vs. one who knows how to copy/paste.
• January 12th, 2012, 12:24 PM
JeremiahWalker
Re: From python to java
My background is actually in IT, and in that field we don't really focus on programming. We are mostly responsible for implementing solutions. I want to learn programming to become more well rounded in the tech-sector. To that end. I wrote most of that code on my own. What I wanted to do with the code was to pick a number from the array (EG the 100th, 1000th 5000th prime number in a sequence). I know that the code is actually printing the array. I also want a variable(int pCounter) to keep track of the primes found in the sieve.
• January 14th, 2012, 12:12 AM
RaoPatek
Re: From python to java
Java Rocks Now and forever...