LargestPrimeFactor.java 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. public class LargestPrimeFactor {
  2. private long value;
  3. // To store the largest prime factor of a given number
  4. private long largestPrimeFactor;
  5. public LargestPrimeFactor(long num) {
  6. this.value = num;
  7. this.largestPrimeFactor = this.setLargestPrimeFactor();
  8. }
  9. // Helper function to find prime numbers
  10. private static boolean checkPrime(long num) {
  11. /* To check whether the number is divisible by any number other than
  12. itself and one */
  13. for (long i = 2; i < num; i++) {
  14. if (num % i == 0)
  15. return false;
  16. }
  17. return true;
  18. }
  19. // Helper function to see if one number is a factor of another
  20. private static boolean checkFactor(long dividend, long divisor) {
  21. return dividend % divisor == 0;
  22. }
  23. // To calculate the largest prime for the current number
  24. private long setLargestPrimeFactor() {
  25. long largestPrimeFactor = 0;
  26. for (long i = 1; i < this.value; i++) {
  27. if ( checkPrime(i) && checkFactor(this.value, i) ) {
  28. largestPrimeFactor = i;
  29. }
  30. else
  31. continue;
  32. }
  33. return largestPrimeFactor;
  34. }
  35. public long getLargestPrimeFactor() {
  36. return this.largestPrimeFactor;
  37. }
  38. }