Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: From python to java

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default 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.

    #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.")


  2. #2
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default 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.

  3. #3
    Junior Member
    Join Date
    Jan 2012
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: From python to java

    good point. I actually wrote that program when I was first starting out in programming.

  4. #4
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default 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.

  5. #5
    Junior Member
    Join Date
    Jan 2012
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default 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

    //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

  6. #6
    Junior Member
    Join Date
    Jan 2012
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default 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

  7. #7
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default 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.
    Last edited by helloworld922; January 12th, 2012 at 12:22 AM.

  8. The Following User Says Thank You to helloworld922 For This Useful Post:

    ChristopherLowe (January 14th, 2012)

  9. #8
    Junior Member
    Join Date
    Jan 2012
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default 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.

  10. #9
    Junior Member
    Join Date
    Jan 2012
    Location
    Mumbai
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: From python to java

    Java Rocks Now and forever...

Similar Threads

  1. Java equivalant of Python re.match()
    By gonzalioz in forum Java Theory & Questions
    Replies: 1
    Last Post: October 30th, 2011, 10:25 AM
  2. Run Python file in Java code
    By soheilz92 in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: May 21st, 2011, 07:33 PM
  3. Replies: 10
    Last Post: April 5th, 2011, 09:09 AM
  4. Java equivalent of Python’s struct.pack?
    By thiruvadi.e in forum Java SE APIs
    Replies: 2
    Last Post: July 14th, 2010, 03:09 AM