Prime factors Learn programming Java

Lesson:

Basic Data Types


Exercise:

Prime factors


Objetive:

Create a java program that displays a number (entered by the user) as a product of its prime factors. For example, 60 = 2 · 2 · 3 · 5

(Hint: it can be easier if the solution is displayed as 60 = 2 · 2 · 3 · 5 · 1)


Code:

import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		int n;
		int d = 2;

		System.out.print("Enter the number: ");
		n = Integer.parseInt(new Scanner(System.in).nextLine());

		while (n > 1)
		{
			while (n % d == 0)
			{
				System.out.print(d);
				System.out.print(" · ");
				n = n / d;
			}

			d++;
		}
		System.out.print(1);
	}
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.