Program Displays the number of Mersenne wrong - java

hi guys the problem that im having with this code is that the number of mersenne primes is supposed to be 4 but it outputs 8. i know this because the number of Mersenne primes between 1 and 1000 are 3, 7, 31, and 127 but it also outputs 15, 63, 255, and 511. which i dont know why. is there also a way to output the counts of Primes per 100 numbers? thanks
public static void main(String[] args) {
System.out.println("Prime numbers between 1 and 1000 are\n");
String message = "";
String message2 = "";
// loop numbers from 1 to 1,000, printing only the primes
int counter2 = 0;
int counter = 0;
for( int number s= 2; number <= 1000; number ++){
if(isPrime(number)) {
counter++;
if(counter % 10 == 0) {
System.out.println(number);
}
else
System.out.print(number + " ");
}
}
for(int number2 = 2; number2 <= 1000; number2 ++){
if(isMersenne(number2)){
counter2++;
System.out.print(number2 + "*");
}
}
System.out.print( "\n\n The number of primes between 1 and 1000 are " + counter);
System.out.print( "\n The number of Mersennes is " + counter2);
}
public static boolean isPrime( int number ){
// initialize the boolean variable prime to true
boolean isPrime = true;
for(int divisor = 2; divisor <= number /2; divisor++) {
if(number % divisor == 0) {
isPrime = false;
}
}
return isPrime;
}
public static boolean isMersenne(int number){
// declare and initialize variable powTwo to 2
int powTwo = 2;
boolean mersenne = false;
while(powTwo <= number){
powTwo *= 2;
if(powTwo - number == 1)
// if the prime is one less than a power of 2, return true
mersenne = true;
}
return mersenne;
} // end method isMersenne
}
this is the output of my program
Prime numbers between 1 and 1000 are
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601
607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997 3*7*15*31*63*127*255*511*
The number of primes between 1 and 1000 are 168
The number of Mersennes is 8

Your problem is that isMersenne is just checking whether the number is one less than a power of two. It's not also checking that it's a prime.
You need to change your isMersenne method so that it calls isPrime after checking whether the number is one less than a power of two. If isPrime returns false, then isMersenne should also return false.

Related

How to create a matrix using predetermined row, column, and value numbers in a string Java

I am stuck and need helpful input with my beginner code. I have a text file that contains:
{001 012 023 034 045 056 067 078 089 102 113 124 135 146 157 168 179 181 203 214 225 236 247 258 269 271 282 304 315 326 337 348 359 361 372 383 405 416 427 438 449 451 462 473 484 506 517 528 539 541 552 563 574 585 607 618 629 631 642 653 664 675 686 708 719 721 732 743 754 765 776 787 809 811 822 833 844 855 866 877 888}
Each triplet corresponds to the X and Y axis for the first two numbers and the value to put in this index is the third one.
Step 1) I buffered in the text and removed spaces to isolate each value(X,Y,Z) in its own string to ease use further out.
Step 2) I convert a specific character in each string to INT giving me 3 values I can then insert manually in my 9X9 matrix.
Step 3) For now I can manually select the index and populate one value in the matrix(in this example, in the code I selected index 8), I need to do this for all values in a loop but can't seem to figure out how to go forward with this.
Code:
import java.io.*;
public class readBuffer {
static void theBuffer() throws IOException {
File file = new File("D://Documents/-/DOCS/School/Prog/game1.txt");
String xString = ""; //three strings used for the coordinates
String yString = "";
String zString = "";
int[][] tab = new int[9][9]; //9X9 matrix created
try (
//read file
FileReader aFile = new FileReader(file);
//
BufferedReader theBuffer = new BufferedReader(aFile);
) {
//Conversion to a String of characters
String string = theBuffer.readLine();
//removes spaces in the string
string = string.replaceAll("\\s", "");
//Loop that generates the X,Y,Z coord and value strings
//Row X (1st value in the triplet)
for (int i = 0, n = string.length(); i < n; i++) {
if ((i + 2) % 3 == 2)
xString += (string.charAt(i));
}
//Column Y (2nd value in the triplet)
for (int i = 0, n = string.length(); i < n; i++) {
if ((i + 1) % 3 == 2)
yString += (string.charAt(i));
}
//Value Z (3rd value in the triplet)
for (int i = 0, n = string.length(); i < n; i++) {
if (i % 3 == 2)
zString += (string.charAt(i));
}
//Visualization for testing
System.out.println("Row #:" + xString);
System.out.println("Col #:" + yString);
System.out.println("Num #:" + zString);
int x = Character.getNumericValue(xString.charAt(8)); //Convert specific char to an INT
int y = Character.getNumericValue(yString.charAt(8)); //Convert specific char to an INT
int z = Character.getNumericValue(zString.charAt(8)); //Convert specific char to an INT
//Visualization for testing
System.out.println("");
System.out.println("//Converted INT numbers//");
System.out.println("Row #:" + x);
System.out.println("Col #:" + y);
System.out.println("Num #:" + z);
//Loop that generates then 9X9 matrix
tab[x][y] = z;
System.out.println("");
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++)
System.out.print(tab[i][j] + " ");
System.out.println();
}
} catch (IOException e) {
System.out.println(e);
}
}
public static void main(String[] args) throws IOException {
theBuffer();
}
}
Image of console Result
Need to fill this out and that is where I need advice.
Seems like you should just iterate the "triplets" and extract the 3 digits.
static int[][] parseMatrix(String values) {
int[][] matrix = new int[9][9];
for (String triplet : values.split(" ")) {
int row = Character.digit(triplet.charAt(0), 10);
int col = Character.digit(triplet.charAt(1), 10);
int val = Character.digit(triplet.charAt(2), 10);
matrix[row][col] = val;
}
return matrix;
}
Test
int[][] matrix = parseMatrix("001 012 023 034 045 056 067 078 089" +
" 102 113 124 135 146 157 168 179 181" +
" 203 214 225 236 247 258 269 271 282" +
" 304 315 326 337 348 359 361 372 383" +
" 405 416 427 438 449 451 462 473 484" +
" 506 517 528 539 541 552 563 574 585" +
" 607 618 629 631 642 653 664 675 686" +
" 708 719 721 732 743 754 765 776 787" +
" 809 811 822 833 844 855 866 877 888");
for (int[] row : matrix) {
for (int value : row)
System.out.print(value + " ");
System.out.println();
}
Output
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 1
3 4 5 6 7 8 9 1 2
4 5 6 7 8 9 1 2 3
5 6 7 8 9 1 2 3 4
6 7 8 9 1 2 3 4 5
7 8 9 1 2 3 4 5 6
8 9 1 2 3 4 5 6 7
9 1 2 3 4 5 6 7 8

Printing data file containing multiple matrixes

I'm running into a problem with a program that I'm writing for a class.
I was given a text file that contains three matrices and I need to create a loop that prints out all three of them in the output through various filters.
Here is what the file contains:
15 15
91 114 75 145 149 250 31 103 88 123 27 120 187 140 52
108 23 43 126 51 9 107 29 20 221 18 41 178 245 159
187 53 7 107 96 82 70 2 171 2 36 84 135 187 92
176 30 199 230 178 61 48 211 208 143 178 207 79 196 217
26 6 117 170 4 245 63 93 108 44 163 19 6 220 131
7 210 228 154 213 96 102 254 63 34 25 215 168 23 207
131 254 198 215 164 6 141 150 147 26 242 199 237 131 240
102 22 248 74 26 3 138 145 132 120 97 126 8 86 166
178 68 73 127 56 180 182 152 3 149 184 42 204 9 172
104 203 99 132 204 137 33 69 140 19 131 38 239 56 180
163 249 88 222 98 150 58 155 115 188 70 189 162 33 1
113 141 52 196 139 241 68 37 89 215 166 7 200 179 26
21 68 167 53 226 167 193 232 133 79 212 163 101 157 233
122 17 114 224 129 247 35 84 120 51 91 149 127 150 19
217 253 145 45 205 179 107 76 214 48 230 218 8 135 25
6 6
201 159 87 63 240 244
231 32 222 76 5 255
10 5 248 139 47 64
167 76 138 177 107 159
188 122 154 165 205 22
222 149 148 85 129 57
5 5
201 159 87 63 240
231 32 222 76 5
10 5 248 139 47
167 76 138 177 107
188 122 154 165 205
I was able to get a loop that read the file and prints out the first 15x15 array, but I need a loop that will print out the other three after it including the filters applied to the data.
That is:
Base image data:
(15x15 array)
(6x6 array)
(5x5 array)
Filtered data:
(15x15 filtered)
(6x6 filtered)
(5x5 filtered)
I'm able to print out the first array just fine, but I am racking my brain trying to find a way to loop the code to print out the other two arrays. Additionally, I have a second problem that when the filtered data is printed, it's all 0s like so:
Base Image Data
91 114 75 145 149 250 31 103 88 123 27 120 187 140 52
108 23 43 126 51 9 107 29 20 221 18 41 178 245 159
187 53 7 107 96 82 70 2 171 2 36 84 135 187 92
176 30 199 230 178 61 48 211 208 143 178 207 79 196 217
26 6 117 170 4 245 63 93 108 44 163 19 6 220 131
7 210 228 154 213 96 102 254 63 34 25 215 168 23 207
131 254 198 215 164 6 141 150 147 26 242 199 237 131 240
102 22 248 74 26 3 138 145 132 120 97 126 8 86 166
178 68 73 127 56 180 182 152 3 149 184 42 204 9 172
104 203 99 132 204 137 33 69 140 19 131 38 239 56 180
163 249 88 222 98 150 58 155 115 188 70 189 162 33 1
113 141 52 196 139 241 68 37 89 215 166 7 200 179 26
21 68 167 53 226 167 193 232 133 79 212 163 101 157 233
122 17 114 224 129 247 35 84 120 51 91 149 127 150 19
217 253 145 45 205 179 107 76 214 48 230 218 8 135 25
Image Filter1:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
The code I have it pretty extensive, so I'm having trouble pinpointing why it's returning 0s.
Here is my code:
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("imagedata.txt"));
int r = scanner.nextInt();
int c = scanner.nextInt();
int [][] imageData = new int[r][c];
//for loop to create 2d array from image data
for(int row=0; row<imageData.length; row++) {
for(int col=0; col<imageData[row].length; col++) {
imageData[row][col] = scanner.nextInt();
}
}
System.out.println("Base Image Data");
for(int[] row : imageData) {
for(int num : row) {
System.out.print(num+" ");
}
System.out.println();
}
System.out.println("Image Filter1:");
int[][] filter1 = applyFilter1(imageData);//call return from applyFilter1
for(int[] row : filter1){
for(int num : row){
System.out.print(num+" ");
}
System.out.println();
}
}
public static int[][] applyFilter1(int[][] imageData){
int[][] filtered = new int[imageData.length][imageData[0].length];
for (int row=0; row<filtered.length;row++){
for (int col=0;col<filtered[row].length;col++){
int[] nebs = getNeighbors(row, col, imageData);
int sum = 0;
for(int i=0; i<nebs.length; i++){
sum = sum + nebs[i];
int average = sum / nebs.length;
filtered[row][col] = average;
}
}
}
return filtered;
}
public static int[] getNeighbors(int row, int col, int[][] imageData){
//find neighbors of current index
int [][] copyImage = new int[imageData.length][imageData[0].length];
try{
for(int r=0; r<imageData.length; r++){
for(int c=0; c<imageData[r].length; c++){
imageData[r][c] = copyImage[r][c];
}
}
} catch(Exception e){
System.out.println("Array copy not successful");
}
//handles the top row of the array
if(row==0){//if copyImage[0].length
if(col==0){//handles upper left corner of array
int[] nebs = {copyImage[row][col], copyImage[row+1][col],
copyImage[row][col+1]};
return nebs;
}
else if(col==copyImage[row].length-1){//handles upper right corner of array
int[] nebs = {copyImage[row][col], copyImage[row][col-1],
copyImage[row+1][col]};
return nebs;
}
else{//handles top row of array between corners
int[] nebs = {copyImage[row][col], copyImage[row][col-1],
copyImage[row+1][col], copyImage[row][col+1]};
return nebs;
}
}
//handles the bottom row of the array
else if(row==copyImage.length-1){//if the row is at max value
if(col==0){//handles botton left corner of array
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row][col+1]};
return nebs;
}
else if(col==copyImage[row].length-1){//handles bottom right corner of array
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row][col-1]};
return nebs;
}
else{//handles bottom row of array
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row][col-1], copyImage[row][col+1]};
return nebs;
}
}
//handles leftmost column of array
else if(col==0){//if col=0 and row increases
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row+1][col], copyImage[row][col+1]};
return nebs;
}
//handles rightmost column of array
else if(col==copyImage[row].length-1){//if col=max value and row increases
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row+1][col], copyImage[row][col-1]};
return nebs;
}
//handles values in the body of the array
else{
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row+1][col], copyImage[row][col-1],
copyImage[row][col+1]};
return nebs;
}
}
I'm still new to java, despite the amount of code in this program. So any guidance and feedback is welcome.
You can simply read this file line-by-line, split each string into an array of numbers, then format them as a three-character string, concatenate them back and output. No matter how many matrices are in this file.
List<String> list = List.of(
"91 114 75 145 149 250 31 103 88 123 27 120 187 140 52",
"108 23 43 126 51 9 107 29 20 221 18 41 178 245 159",
"187 53 7 107 96 82 70 2 171 2 36 84 135 187 92");
list.stream()
.map(str -> Arrays
// split string into an array of numbers
.stream(str.split("\s+"))
// format as a three-character string
.map(s -> String.format("%3s", s))
// concatenate into a single string
.collect(Collectors.joining(" ")))
// output line by line
.forEach(System.out::println);
Output:
91 114 75 145 149 250 31 103 88 123 27 120 187 140 52
108 23 43 126 51 9 107 29 20 221 18 41 178 245 159
187 53 7 107 96 82 70 2 171 2 36 84 135 187 92

How can I find the max number in the code?

I want my code to print out 10 numbers per line and count how many numbers there are. I also want to be able to find the max number. I am having trouble figuring out how to find the max. Here is my code.
int valCount = 0;
int numCount =0;
while (startingNum > 1) {
int count = 0;
System.out.print(startingNum + " ");
valCount++;
if(valCount%10 ==0)
System.out.println();
if (startingNum % 2==0) {
startingNum = startingNum/2;
numCount++;
} else {
startingNum = (startingNum*3) +1;
numCount++;
}
}
This is the correct code:
public static void main(String[] args) {
int startingNum = 27;
int counter = 0;
while (startingNum > 1) {
counter++;
System.out.print(startingNum + " ");
if (counter % 10 == 0)
System.out.println();
if (startingNum % 2 == 0) {
startingNum = startingNum / 2;
} else {
startingNum = (startingNum * 3) + 1;
}
}
System.out.println(1);
}
You can use a counter, increment it at each print, when you reach a multiple of 10 print a new line, also to align the different elements, I would suggest to use printf, here I set to %5d because max number has 4 digit, if it goes up to like 6 digit use %7d
int valCount = 0;
while (startingNum > 1) {
System.out.printf("%5d", startingNum);
valCount++;
if(valCount%10 ==0)
System.out.println();
if (startingNum % 2==0) {
startingNum = startingNum/2;
} else {
startingNum = (startingNum*3) +1;
}
}
System.out.printf(" 1");
The Demo code will give you :
27 82 41 124 62 31 94 47 142 71
214 107 322 161 484 242 121 364 182 91
274 137 412 206 103 310 155 466 233 700
350 175 526 263 790 395 1186 593 1780 890
445 1336 668 334 167 502 251 754 377 1132
566 283 850 425 1276 638 319 958 479 1438
719 2158 1079 3238 1619 4858 2429 7288 3644 1822
911 2734 1367 4102 2051 6154 3077 9232 4616 2308
1154 577 1732 866 433 1300 650 325 976 488
244 122 61 184 92 46 23 70 35 106
53 160 80 40 20 10 5 16 8 4
2 1

How to print all possible sequences of a number n

I am trying to print all possible sequences of n and I don't know where I went wrong.
Example: If I let n = 3, then I have to get 33 possible combinations.
import java.util.Scanner;
public class MyPermutations {
public static void show(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.printf("%d", a[i]);
System.out.printf("\n");
}
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static boolean hasNext(int[] a) {
int N = a.length;
// find rightmost element a[k] that is smaller than element to its right
int k;
for (k = N-2; k >= 0; k--)
if (a[k] < a[k+1]) break;
if (k == -1) return false;
// find rightmost element a[j] that is larger than a[k]
int j = N-1;
while (a[k] > a[j])
j--;
swap(a, j, k);
for (int r = N-1, s = k+1; r > s; r--, s++)
swap(a, r, s);
return true;
}
public static void perm(int N) {
// initialize permutation
int[] a = new int[N];
for (int i = 1; i < N; i++) {
a[0]=1;
a[i] = i+1;
}
// print permutations
show(a);
while (hasNext(a))
show(a);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = Integer.parseInt(sc.next());
perm(N);
}
}
Input:
3
My Output:
123 132 213 231 312 321
Expected Output:
111 112 113 121 122 123 131 132 133
211 212 213 221 222 223 231 232 233
311 312 313 321 322 323 331 332 333
Forget about swap, and start over.
Think of it like incrementing a number, except you can only use digits 1-N.
E.g. for N=4, start with 1111. Print it.
Increment to 1112, then 1113, then 1114.
Next increment carries over, so 1121, 1122, ..., 1144.
Handle multiple carry overs, 1211.
And so on until you reach 4444, and you're done.
Of course, you could just loop through the N^N combinations, and use division and remainder to build to "digits" for each combination:
private static void perm(int n) {
char[] digits = new char[n];
final int combinations = (int)Math.pow(n, n);
for (int i = 0; i < combinations; i++) {
for (int num = i, j = n - 1; j >= 0; num /= n, j--)
digits[j] = (char)('1' + num % n);
System.out.print(digits);
System.out.print((i + 1) % (n * n) == 0 ? System.lineSeparator() : " ");
}
}
Output
// perm(1)
1
// perm(2)
11 12 21 22
// perm(3)
111 112 113 121 122 123 131 132 133
211 212 213 221 222 223 231 232 233
311 312 313 321 322 323 331 332 333
// perm(4)
1111 1112 1113 1114 1121 1122 1123 1124 1131 1132 1133 1134 1141 1142 1143 1144
1211 1212 1213 1214 1221 1222 1223 1224 1231 1232 1233 1234 1241 1242 1243 1244
1311 1312 1313 1314 1321 1322 1323 1324 1331 1332 1333 1334 1341 1342 1343 1344
1411 1412 1413 1414 1421 1422 1423 1424 1431 1432 1433 1434 1441 1442 1443 1444
2111 2112 2113 2114 2121 2122 2123 2124 2131 2132 2133 2134 2141 2142 2143 2144
2211 2212 2213 2214 2221 2222 2223 2224 2231 2232 2233 2234 2241 2242 2243 2244
2311 2312 2313 2314 2321 2322 2323 2324 2331 2332 2333 2334 2341 2342 2343 2344
2411 2412 2413 2414 2421 2422 2423 2424 2431 2432 2433 2434 2441 2442 2443 2444
3111 3112 3113 3114 3121 3122 3123 3124 3131 3132 3133 3134 3141 3142 3143 3144
3211 3212 3213 3214 3221 3222 3223 3224 3231 3232 3233 3234 3241 3242 3243 3244
3311 3312 3313 3314 3321 3322 3323 3324 3331 3332 3333 3334 3341 3342 3343 3344
3411 3412 3413 3414 3421 3422 3423 3424 3431 3432 3433 3434 3441 3442 3443 3444
4111 4112 4113 4114 4121 4122 4123 4124 4131 4132 4133 4134 4141 4142 4143 4144
4211 4212 4213 4214 4221 4222 4223 4224 4231 4232 4233 4234 4241 4242 4243 4244
4311 4312 4313 4314 4321 4322 4323 4324 4331 4332 4333 4334 4341 4342 4343 4344
4411 4412 4413 4414 4421 4422 4423 4424 4431 4432 4433 4434 4441 4442 4443 4444
If you look at your output, the problem is obvious. You are not accounting for multiple instances of the same number (i.e. 2 2's or 3 3's).
If you want all possible permutations your code is just fine, as permutations are made from swapping elements only and not reusing them.
If you want to build all possible combinations (including aaa, aab, etc.) instead it won't be enough to just swap the elements.
public List<String> combinations(List<Character> elements) {
List<String> combinations = new ArrayList<>();
if (elements.isEmpty()) {
return combinations;
}
if (elements.size() == 1) {
combinations.add(String.valueOf(elements.get(0)));
return combinations;
}
for (int i = 0; i < elements.size(); i++) {
int current = elements.get(i);
List<String> subCombinations = combinations(elements);
StringBuilder builder;
for (String s : subCombinations) {
builder = new StringBuilder();
builder.append(current).append(s);
combinations.add(builder.toString());
}
}
return combinations;
}

Optimize runtime for finding nth prime number

This is a Java program that finds the nth prime number in a given range.
The max range that can be input is 1-1500000.
The code output is correct for all the possible test cases, but has to be optimized for runtime. What optimization techniques can be applied in this code?
import java.io.*;
class prime
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String m1,m2,m;
int n1=0,n2=0,n=0;
try
{
//input as string instead of integer because errors must be displayed only after all the values have been input
m1=br.readLine(); //range minimum value
m2=br.readLine(); //range max value
m=br.readLine(); //nth value in range
n1=Integer.parseInt(m1);
n2=Integer.parseInt(m2);
n=Integer.parseInt(m);
if(n1<0||n2>1500000||n1>n2||n==0)
throw new Exception();
}
catch(Exception e)
{
System.out.println("Invalid Input");
System.exit(0);
}
int k=n1,count=0,count1=0;
while(k<=n2&&count1<=n)
{
count=0;
for(int i=1;i<=k;i++)
{
if(k%i==0)
count++;
}
if(count==2)
{
count1++;
}
k++;
}
if(count1==n)
{
System.out.println(k);
System.exit(0);
}
if(count1<n)
{
System.out.println("No prime number is present at this index");
System.exit(0);
}
}
}
Don't test "has exactly 2 divisors", test "is not divisible by numbers other than 1 and itself".
Don't test all values <= k as divisors, test all values <= sqrt(k).
(If a number is divisible by a number greater than sqrt(k), then the result of the division is also an divisor, but would have been found earlier)
Maybe reuse already calculated primes; You only need to test prime numbers as possible divisors. However you need to be careful. If you e.g. search in range 9999-9999, it doesn't make sense to calculate all the smaller primes, however if the range is 1-9999, it reduces the number of checks you have to make. You could combine both approaches and test numbers smaller than n1 the "normal" way and test all larger divisors using the primes you already found.
Your loop can be rewritten like this to apply 1. and 2.:
int k=Math.max(2, n1); // 0 and 1 are no prime
int count1 = 0;
while(k <= n2 && count1 <= n) {
final int sqrt = (int) Math.sqrt(k);
count1++; // asume it's a prime
for(int i = 2; i <= sqrt; i++) {
if(k % i == 0) {
// divisible by number other than 1 and itself -> not a prime
count1--;
break;
}
}
k++;
}
This reduces the running time from O((n2)² - (n1)²) to
Check for divisors between 2 and square root of k. If you don't find any, you've found a prime.
int k=n1,count1=0;
while(k<=n2&&count1<=n)
{
boolean isPrime = true;
for(int i=2;i <= Math.sqrt(k) ;i++)
{
if(k%i==0)
{
isPrime = false;
break;
}
}
if (isPrime)
count1++;
k++;
}
Also, you can handle 2 explicitly and skip every other even number.
As your maximum value is limited, it makes sense to keep a table of the primes from 2 to 1229 (1229² = 1510441) and try them in turn until the number gets smaller than the square of the prime. 2 can be tested without a division. You can also store a table of the squares.
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601
607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997 1009 1013
1019 1021 1031 1033 1039 1049 1051 1061 1063 1069
1087 1091 1093 1097 1103 1109 1117 1123 1129 1151
1153 1163 1171 1181 1187 1193 1201 1213 1217 1223
1229

Categories