Tutorialspoint
Problem
Solution
Submissions

Find the Largest Prime Factor of a Number

Certification: Basic Level Accuracy: 66.67% Submissions: 33 Points: 10

Write a Python program that finds the largest prime factor of a given number.

Example 1
  • Input: number = 56
  • Output: 7
  • Explanation:
    • Step 1: Find all prime factors of 56.
    • Step 2: Divide 56 by 2 as many times as possible: 56 ÷ 2 = 28, 28 ÷ 2 = 14, 14 ÷ 2 = 7.
    • Step 3: Now we have 7, which is not divisible by 2.
    • Step 4: Check if 7 is divisible by 3 or any other prime number less than √7. It's not.
    • Step 5: Therefore, 7 is a prime number and is the largest prime factor of 56.
    • Step 6: Return 7.
Example 2
  • Input: number = 13
  • Output: 13
  • Explanation:
    • Step 1: Find all prime factors of 13.
    • Step 2: 13 is not divisible by 2, 3, or any number less than √13.
    • Step 3: Therefore, 13 is a prime number itself and is its own largest prime factor.
    • Step 4: Return 13.
Constraints
  • 2 ≤ number ≤ 10^12
  • Time Complexity: O(sqrt(n)) where n is the input number
  • Space Complexity: O(1)
NumberControl StructuresTutorialspointGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Start by dividing the number by 2 repeatedly until it's no longer divisible
  • Then check for divisibility by odd numbers starting from 3
  • You only need to check potential factors up to the square root of the number

The following are the steps to solve:


  • Define a function count_primes_in_range(start, end).
  • Inside the function, define a helper function to check if a number is prime.
  • If a number is less than or equal to 1, it is not prime.
  • If a number is 2 or 3, it is prime.
  • It is not prime if a number is divisible by 2 or 3.
  • Check divisibility by numbers of the form 6k±1 up to the square root of the number.
  • Iterate through the range and count prime numbers.
  • Call the function and print the result.

Submitted Code :