· 8 years ago · Jun 11, 2018, 10:16 PM
1import java.util.*;
2import java.sql.*;
3
4public class prime {
5
6 public static void main(String[] args) {
7
8 /*
9 * post
10 */
11
12 // Creating database connection
13 String db_location_mac = "jdbc:sqlite:/Users/ShaunHo/Desktop/primes.db";
14 Connection conn = null;
15 try {
16 conn = DriverManager.getConnection(db_location_mac);
17 if (conn != null) {
18 System.out.println("Created new database primes.db");
19 }
20
21 // Wipe the table, and create a new table of primes
22 Statement stmt = conn.createStatement();
23 stmt.executeUpdate("drop table if exists primes");
24 stmt.executeUpdate("create table if not exists primes (prime integer)");
25
26 // Use our function to get the prime numbers and store them
27 addPrimesToDB(stmt);
28
29 // Print out all of the numbers in our 'primes' table
30 ResultSet rs = stmt.executeQuery("select prime from primes");
31 while (rs.next()) {
32 System.out.println(rs.getString(1));
33 }
34
35 } catch (SQLException e) {
36 System.out.println(e.getMessage());
37 }
38
39
40 }
41
42 /*
43 * @pre Takes a Statement from SQLite database and adds primes to the database
44 */
45
46 public static void addPrimesToDB(Statement stmt) throws SQLException {
47 Scanner keyboard = new Scanner(System.in);
48
49 System.out.print("Enter number greater than 1: ");
50 int n = keyboard.nextInt();
51
52 boolean[] primeNumbers = new boolean[n + 1];
53
54 for(int i = 2; i < primeNumbers.length; i++ ) {
55 primeNumbers[i] = true;}
56
57 for(int i = 2; i < primeNumbers.length; i++) {
58 if(primeNumbers[i] == true)
59 {
60 for(int x = 0; ; x++)
61 {
62 int indexFalse = (int) (Math.pow(i, 2) + i*x);
63 if(indexFalse >= primeNumbers.length)
64 break;
65 primeNumbers[indexFalse] = false;
66 }
67 }
68
69 }
70
71 for(int i = 2; i <= n; i++ )
72 {
73 if(primeNumbers[i]) {
74 String sql_command = String.format("insert into primes (prime) values (%d)", i);
75 stmt.executeUpdate(sql_command);
76 }
77 }
78
79 }
80
81}