Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / July 2006

Tip: Looking for answers? Try searching our database.

Displaying factors using Recursion

Thread view: 
smshinde@gmail.com - 29 Jul 2006 08:07 GMT
Hello,
I have written a Recursive function to display integer factors of an
integer.
I am not getting the exit condition for recursion.
Can anyone suggest one.

class Factorize{
static void factorize(int n){
int i=2;
while(true){

if (n%i==0)
{
System.out.print(i+",");
n=n/i;
factorize(n);
}
else i++;
}
}

public static void main(String args[]) {
int n= Integer.parseInt(args[0]);
System.out.println("Genereting Perfect Numbers....");
System.out.print(1+",");
PerfectNumber.factorize(n);
}
}

Output:
C:\sameer>java Factorize 100
Genereting Perfect Numbers....
1,2,2,5,5,
It hangs after this.
Andrey Kuznetsov - 29 Jul 2006 08:14 GMT
> I have written a Recursive function to display integer factors of an
> integer.
[quoted text clipped - 15 lines]
> }
> }

there are 2 conditions, i must be lesser than or equals to n and n must be
greater than 0.

Andrey

Signature

http://uio.imagero.com Unified I/O for Java
http://reader.imagero.com Java image reader
http://jgui.imagero.com Java GUI components and utilities

Stefan Ram - 29 Jul 2006 08:46 GMT
>Can anyone suggest one.

public class Main
{
 static void printFactorsOf( final int n )
 { boolean found = false; int factor;
   for( factor = 2; factor <= n && !( found = n % factor == 0 ); ++factor );
   if( found )
   { java.lang.System.out.print( "*" + factor );  
     printFactorsOf( n / factor ); }}

 public static void printTheFactorsOf( final int n )
 { java.lang.System.out.print( "1" );
   printFactorsOf( n );
   java.lang.System.out.println( "." ); }

 public static void main( final java.lang.String[] commandLineArguments )
 { for( int n = 1; n < 20; ++n )
   { java.lang.System.out.print( n + ": " ); printTheFactorsOf( n ); }}}


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.