Results 1 to 2 of 2
  1. #1
    Raaj71 is offline Member
    Join Date
    Oct 2013
    Posts
    1
    Rep Power
    0

    Default My First Java Program

    Hi there !

    I have recently started learning Java myself with the help of books and online material available. Collected few practice programs. While trying out one of them that is Printing pyramid of prime numbers, i have stucked between loops about how to shift to next line.

    The output I want is like that :

    2
    3 5
    7 11 13
    17 19 23 29
    31 37 41 43 47
    53 59 61 67 71 73

    So far I have written code as below :

    Java Code:
    class Prime
    {
    	public static void main(String args[])
    	{
    		int prime, row, col, div, flag;
    		prime=10;
    		for(row=0; row<=3;row++)
    		{
    			for(col=0;col<=row;col++)
    			{
    				flag=0;
    				for(div=1;div<prime;div++)
    				{
    					if(prime%div==0)
    					{
    						flag++;
    						if(flag>1)
    							break;
    					}
    				}
    				if(flag==1)
    				{
    					System.out.print(prime+" ");
    				}
    				prime++;
    			}
    			System.out.println("");
    		}
    	}
    }
    But its not providing the formatting as I want.

    The output of the above code is :

    11
    13
    17 19


    Have been trying for continuously 2 hours and still not to find the error. Please help.

  2. #2
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,511
    Rep Power
    5

    Default Re: My First Java Program

    The problem is with the distribution of primes. So you cannot depend on rows and columns alone to determine when
    to print a new line. You need to count the primes generated against a running maximum per line. When you print a new line,
    set the count to zero and bump the maximum by one.

    Also, if you think about the nature of primes (even vs odd), remainders, etc you can significantly improve your algorithm.
    For more on this check out the Sieve of Erastosthenes.

    Regards,
    Jim
    Last edited by jim829; 10-08-2013 at 04:46 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

Similar Threads

  1. Replies: 4
    Last Post: 11-21-2012, 01:19 PM
  2. Call one Java Program from another Java Program
    By rajpalparyani in forum New To Java
    Replies: 3
    Last Post: 02-14-2011, 04:13 AM
  3. execute java program within java program
    By popey in forum New To Java
    Replies: 2
    Last Post: 10-22-2009, 05:32 PM
  4. Replies: 0
    Last Post: 04-04-2008, 02:40 PM
  5. Replies: 0
    Last Post: 10-04-2007, 09:33 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •