program to get prime factors of a number code example

Example 1: How could you find all prime factors of a number?

function primeFactors(n){
  var factors = [], 
      divisor = 2;
  
  while(n>2){
    if(n % divisor == 0){
       factors.push(divisor); 
       n= n/ divisor;
    }
    else{
      divisor++;
    }     
  }
  return factors;
}

> primeFactors(69);
  = [3, 23]

Example 2: prime factorization in c

#include <stdio.h>
#define MIN 100
#define MAX 100000


int main(){
    int pdiv=2,j;
    for (int num=MIN;num<=MAX;num++){
        printf("The prime factors of %d are:\n",num);
        j=num;
        do {
            
            if (j%pdiv==0)
            {
                
                printf("%d\n",pdiv);
                j=j/pdiv;
            }else
            {
               pdiv++; 
            }
            
            
        }while(j>1);
        pdiv=2;
        
    }



}

Example 3: Prime factors of a number

public List<Integer> factorsOf(int n) {
  ArrayList<Integer> factors = new ArrayList<>();

  for (int d = 2; n > 1; d++)
    for (; n % d == 0; n /= d)
      factors.add(d);

  return factors;
}

Tags:

C Example