Prime Factors

Calculate the prime factors of a number.

30 = 2 * 3 * 5
40 = 2^3 * 5
2 = 2

Approach:
  • Go through 2..sqrt(N) and check the prime numbers divisible by the number. 
  • If it's divisible then divide the number until the number is not divisible by the given number.
Here is a dry run
  • i = 2, n = 40, ans = [] => 40 is divisible by 2, divide it until 40 is not divisible by 2
  • i = 3, n = 5, ans = [ 2 ] => 5 is not divisible by 3
  • i = 4, n = 5, ans = [ 2 ]
  • i = 5, ans = [ 2, 5 ], 5 is divisible by 5
  • i = 1, ans = [ 2, 5 ], end the loop when i = 1

Code it up:


Comments