Untitled
unknown
java
4 years ago
3.1 kB
8
Indexable
import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Admins */ public class PrimeList { int primeCount; int[] primeList; public static void main(String[] args) { PrimeList pl = new PrimeList(); int[] number = pl.inputData(); pl.processData(number); pl.displayData(); } public int[] inputData() { primeCount = 0; primeList = new int[300]; Scanner sc = new Scanner(System.in); System.out.println("Input Number:"); int intNumber = sc.nextInt(); String temp = Integer.toString(intNumber); int[] number = new int[temp.length()]; //convert input number to array for (int i = 0; i < temp.length(); i++) { number[i] = temp.charAt(i) - '0'; } return number; } public int[] swapDigit(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } int arrayToInt(int[] arr) { //using a Stringbuilder is much more efficient than just using += on a String. //if this confuses you, just use a String and write += instead of append. StringBuilder s = new StringBuilder(); for (int i : arr) { s.append(i); //add all the ints to a string } return Integer.parseInt(s.toString()); //parse integer out of the string } public void processData(int[] number) { int tempNumb1 = arrayToInt(number); if (isPrime(tempNumb1)) { primeList[primeCount] = tempNumb1; primeCount++; } System.out.println("Swapping number:"); for (int i = 0; i < 5; i++) { for (int j = i + 1; j < 5; j++) { int[] temp = swapDigit(number, i, j); int tempNumb = arrayToInt(temp); System.out.println(tempNumb); if (isPrime(tempNumb)) { primeList[primeCount] = tempNumb; primeCount++; } //swap back to origin array number = swapDigit(number, j, i); } } } private boolean isPrime(int n) { // Corner case if (n <= 1) { return false; } // Check from 2 to square root of n for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } public void displayData() { System.out.println("List prime number:"); for (int i = 0; i < primeList.length; i++) { if (primeList[i] == 0) { break; } System.out.print(primeList[i] + " "); } System.out.println("\n--- End ---"); } }
Editor is loading...