Search code examples
javaprime-factoringdiamond-operator

Prime Factors, Alternative to Diamond Brackets


I am trying to write a program that prints ALL prime factors, as well as specify the smallest prime factor of the number from user input. (e.g. If 12 is given, prime factors are 2, 2, and 3.) I have done a bit of searching, but all results for programs that remember all prime factors seem to use <>. For some reason, this is not recognized. I was wondering if there was an alternative way around this?

Edit: I have successfully printed lowest factors, but am still having trouble with printing all prime factors. Edited code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class PrimeFactor {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    System.out.println("Please enter an integer");
    long n = in.nextLong();
    System.out.println("Smallest prime factor of "+n+" is "+leastFactor(n));
}

public static ArrayList<Integer> leastFactor(long n) {
    ArrayList primeFactors = new ArrayList<Integer>();
    for (int i=2; i<=n; i++) {
        if (n%i==0) {
            primeFactors.add(i);
        }
    }

    if(primeFactors.size() > 0){
        return (primeFactors);
    }
}
}

Solution

  • Scanner z = new Scanner(System.in);
    //int n;
    long n;//long to display all prime factors.
    List primefactors = new ArrayList():
    System.out.print("Enter a Number : ");
    //n= z.nextInt();
    n = z.nextLong();
    System.out.print("The Prime Factors of "+n+" are : "); 
    int i=2;
    while(n>1)
      {
       if(n%i == 0)
        {
         primefactors.add(i);
         n=n/i;
        }
       else
        i++;
      }
    System.out.println(Collections.min(primefactors));
    primefactors.forEach(System.out::println);//to display all values
    

    Hope you found my code useful.