-
-
Save bytecodeman/774a7fcdd37051a3bdf08c36ff82afd4 to your computer and use it in GitHub Desktop.
Silvestri's Solution to Emirp Homework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Name: Prof. Antonio C. Silvestri | |
* Date: 09/16/18 | |
* Course Number: CSC-220 | |
* Course Name: Data Structures | |
* Problem Number: HW1 | |
* Email: silvestri@stcc.edu | |
* Short Description of the Problem | |
*/ | |
import java.util.Scanner; | |
public class EmirpGenerator { | |
private static boolean isPrime(int num) { | |
for (int i = 2; i <= (int) (Math.sqrt(num)); i++) | |
if (num % i == 0) | |
return false; | |
return true; | |
} | |
private static int reverseInt(int num) { | |
int revInt = 0; | |
int sign = 1; | |
if (num < 0) { | |
sign = -1; | |
num = -num; | |
} | |
while (num > 0) { | |
int lastDigit = num % 10; | |
revInt = 10 * revInt + lastDigit; | |
num /= 10; | |
} | |
return sign * revInt; | |
} | |
private static boolean isPalindromic(int num) { | |
return num == reverseInt(num); | |
} | |
private static boolean isEmirp(int num) { | |
if (!isPrime(num)) | |
return false; | |
if (isPalindromic(num)) | |
return false; | |
if (!isPrime(reverseInt(num))) | |
return false; | |
return true; | |
} | |
private static String generateEmirps(int start, int noOfEmirps) { | |
String output = ""; | |
int count = 0; | |
int num = start; | |
while (count < noOfEmirps) { | |
if (isEmirp(num)) { | |
output += String.format("%7d ", num); | |
count++; | |
if (count % 10 == 0) | |
output += "\n"; | |
} | |
num++; | |
} | |
return output; | |
} | |
// ********************************************** | |
private static void process(Scanner sc, String args[]) { | |
System.out.print("Enter Emirp Starting Point: "); | |
int start = sc.nextInt(); | |
System.out.print("Enter number of Emirps: "); | |
int noOfEmpirps = sc.nextInt(); | |
sc.nextLine(); // IMPORTANT!! Reset Scanner | |
String output = generateEmirps(start, noOfEmpirps); | |
System.out.println(output); | |
} | |
// ********************************************** | |
private static boolean doThisAgain(Scanner sc, String prompt) { | |
System.out.print(prompt); | |
String doOver = sc.nextLine(); | |
return doOver.equalsIgnoreCase("Y"); | |
} | |
// ********************************************** | |
public static void main(String args[]) { | |
final String TITLE = "EMIRP Generator V1.1"; | |
final String CONTINUE_PROMPT = "Do this again? [y/N] "; | |
System.out.println("Welcome to " + TITLE); | |
Scanner sc = new Scanner(System.in); | |
do { | |
process(sc, args); | |
} while (doThisAgain(sc, CONTINUE_PROMPT)); | |
sc.close(); | |
System.out.println("Thank you for using " + TITLE); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment