Prime Factorization Program in Java

后端 未结 12 1601
自闭症患者
自闭症患者 2021-01-03 11:11

I am working on a prime factorization program implemented in Java. The goal is to find the largest prime factor of 600851475143 (Project Euler problem 3). I think I have m

12条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 12:01

    public class Prime
    {
     int i;   
    
     public Prime( )
     {
        i = 2;
     }
    
     public boolean isPrime( int test ) 
     {
        int k;
    
        if( test < 2 )
            return false;
        else if( test == 2 )  
            return true;
        else if( ( test > 2 ) && ( test % 2 == 0 ) )
            return false;
        else
        {
            for( k = 3; k < ( test/2 ); k += 2 )
            {
                if( test % k == 0 ) 
                    return false;
            }
    
        }
    
        return true;
    
     }
    
     public void primeFactors( int factorize )
     {
        if( isPrime( factorize ) )
        {
            System.out.println( factorize );
            i = 2;
        }
        else
        {
            if( isPrime( i ) && ( factorize % i == 0 ) )
            {
                System.out.print( i+", " );
                primeFactors( factorize / i );
            }
            else
            {
                i++;
                primeFactors( factorize );
            }
       }
    
       public static void main( String[ ] args )
       {
           Prime p = new Prime( );
    
           p.primeFactors( 649 );
           p.primeFactors( 144 );
           p.primeFactors( 1001 );
       }
    }
    

提交回复
热议问题