Question

Q. How to write a recursive algorithm to find the largest prime factor of a number...

Q. How to write a recursive algorithm to find the largest prime factor of a number in java?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.io.*;

import java.util.*;

class GFG {

    // function to find largest prime factor

    static long maxPrimeFactors(long n)

    {

        // Initialize the maximum prime

        // factor variable with the

        // lowest one

        long maxPrime = -1;

        // Print the number of 2s

        // that divide n

        while (n % 2 == 0) {

            maxPrime = 2;

            // equivalent to n /= 2

            n >>= 1;

        }

        // n must be odd at this point,

        // thus skip the even numbers

        // and iterate only for odd

        // integers

        for (int i = 3; i <= Math.sqrt(n); i += 2) {

            while (n % i == 0) {

                maxPrime = i;

                n = n / i;

            }

        }

        // This condition is to handle

        // the case when n is a prime

        // number greater than 2

        if (n > 2)

            maxPrime = n;

        return maxPrime;

    }

    // Driver code

    public static void main(String[] args)

    {

        Long n = 15l;

        System.out.println(maxPrimeFactors(n));

        n = 25698751364526l;

        System.out.println(maxPrimeFactors(n));

    }

}


Output:

5
328513
Add a comment
Know the answer?
Add Answer to:
Q. How to write a recursive algorithm to find the largest prime factor of a number...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT