Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
public class primzahlen {
public static void main(String[] args) {
System.out.println(2 % 1);
calculate_primenumber(10);
}
static void calculate_primenumber(int a) {
int zahl = 1;
boolean isprimenumber = false;
for (int i = 1; i <= a; i++) {
for (int j = 1; j <= i; j++) {
if (i % j > 0) {
// No PrimeNumber
isprimenumber = false;
} else {
// Is PrimeNumber
isprimenumber = true;
zahl = i;
System.out.println(zahl);
}
}
}
}
}
I don't know why this doesn't work.
I want to calculate 10 prime numbers.
But somehow it only prints counts up to 10 3 times and thats it.
I don't know wheres my mistake.
I have 2 for loops. That's how I learned the prime numbers calculation that I have to use 2 for loops for it but it don't work. I thought first it is the % (the rest) but when I do it on paper it should work.
There are at least four things wrong with your code.
First, you have the % condition backwards. If you're testing the number i, and you want to see if it has a divisor j, then you need to test i % j == 0. If this is true, the number is not prime. The way you tested it, though, you told it that if i % j is not zero, then the number is not prime.
Second, when you test to see if something divides i, you cannot test 1, and you cannot test i itself. Therefore,
for (int j = 1; j <= i; j++) {
should look more like
for (int j = 2; j < i; j++) {
although it's usually
for (int j = 2; j < Math.sqrt(i); j++) {
since once you get past the square root of i you don't need to search any more.
Third: your inner loop sets isprimenumber to either true or false on every iteration. That isn't right. If we find a case where i has a divisor, we know that isprimenumber is false, and we should never set it to true again, for that i. So a loop like this would work:
isprimenumber = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
// No PrimeNumber
isprimenumber = false;
}
// If it's non-zero, don't set isprimenumber to true, because if we
// set it to false earlier, then it still should be false!
}
// And wait until we've tested all the j's before we can tell if it's true.
if (isprimenumber) {
}
You can also put break after isprimenumber = false, because once we've found a divisor we don't need to keep looking.
for (int j = 2; j < i; j++) {
if (i % j == 0) {
// No PrimeNumber
isprimenumber = false;
break;
}
Without the break, the loop will go on a few more times but it won't do anything useful. (But it won't be harmful, either.)
Fourth, you said you want to print 10 primes, but your logic tested all the numbers from 1 to 10, and there aren't 10 primes in that range. If you want the first 10 primes, where your parameter a is 10, you can't stop the loop at i <= a:
for (int i = 1; i <= a; i++) {
Instead, you'll need to declare another counter to count the number of primes.
int count = 0;
and when you find a prime and print it:
count++;
Then you could write your for loop like this:
for (int i = 1; count < a; i++) {
and it will stop when the number of primes reaches a.
EDIT: There's one more error I missed: the code I suggested will find that 1 is a prime number, but technically it isn't (so say the mathematicians). So you should start at i = 2:
for (int i = 2; count < a; i++) {
"I want to check for 10 prime numbers"
When you say
for (int i = 1; i <= a; i++)
You are saying "the numbers from 1 to a," which in this case is 1 to 10. Thus, you can only check 1 through 10 for primality. a is the upper bound you place on the numbers to check for primality.
If you want to get the first 10 prime number instead, you are going to have to use a condition which checks for the number of primes you have discovered (and keep count of that).
"It only prints counts up to 10 3 times and thats it"
Your modulus check should be (i % j == 0) - this means that j evenly divides i, and is therefore a factor of i. As you stand, you are saying that if any j is not a factor of i, the number is immediately composite. Not only is this not a correct conclusion, but it jumps the gun on your decision. You should assume it is prime until you can prove it is composite - then you can decide early.
One thing to keep in mind is the fact that a number, mod itself, is always 0. The same goes for a number mod 1. So, you will have to make sure you do not compare any i with itself or with 1. Change the second for loop to stop when j < i and to start with j = 2.
for (int i = 1; i <= a; i++) {
isprimenumber = true;
for (int j = 2; j < i; j++) {
// check each number less than this one for factors
if (i % j == 0) {
// found an even divisor, so the number is composite
isprimenumber = false;
break;
}
}
if (isprimenumber) {
System.out.println(i);
}
}
You can make other optimizations by noting that 1 is generally not considered a prime number, so you can have your first loop be for (int i = 2; i <= a; i++) and also considering that there are no even divisors of a number greater than one half of that number, so you can have your second loop be for (int j=2; j < i/2; j++).
This is one way
public class Primzahlen {
public static void main(String[] args){
calculate_primenumber(10);
}
static void calculate_primenumber(int a) {
int primesFound = 0;
boolean isprimenumber;
for(int i = 2; primesFound < a; i++){
isprimenumber = true;
for(int j = 2; j < i ; j++){
if(i % j == 0){
isprimenumber = false;
break;
}
}
if(isprimenumber){
primesFound++;
System.out.println(i);
}
}
}
}
but you can make it more efficient. This is only one way : klick
You must do the true thing on the end of the loop like this:
for (int i = 1; i <= a; i++) {
for (int j = 1; j <= i; j++) {
if (i % j > 0) {
// No PrimeNumber
isprimenumber = false;
} else {
// Is PrimeNumber
isprimenumber = true;
}
}
if(isprimenumber)
System.out.println(i);
}
you can only tell its a prime if you tested all numbers.
Related
I want to find the smallest number that can be divided with no reminder(perfect division) by the first 20 numbers (1, 2, 3... 20).
I've tried something that I thought would not fail, that goes like this:
for (int i = 20; i < Integer.MAX_VALUE; i++) {
int seImparte = 0;
for (int j = 1; j <= 20; j++) {
if (i % j != 0) {
seImparte++;
}
}
if (seImparte == 0) {
System.out.println(i);
break;
}
}
I thought I would get the first number and then the program would exit, but it runs and nothing happens.
Thank you for your time and help!
#raulGLD Your code works fine but it is not optimezed,
You can break inner loop, after invalid condition
Also you can start from 3 or 7 as [1,2,3,4,5,6 can be tested by [4,6,8,10,12] -This is optional but break is important
for (int i = 20; i < Integer.MAX_VALUE; i++) {
int seImparte = 0;
for (int j = 7; j <= 20; j++) {
if (i % j != 0) {
seImparte++; break;
}
}
if (seImparte == 0) {
System.out.println(i);
break;
}
}
output : 232792560
Instead of optimizing of brute-force approach, it is worth to use simple math rules.
Resulting complexity is O(n*log(n)) against "huge count"
Python code uses Least common multiple function
def gcd(a, b):
while b > 0:
a, b = b, a % b
return a
def lcm(a, b):
return a * b // gcd(a, b) # integer division
d = 1
for i in range(2, 21): #last i=20
d = lcm(d, i)
print(d)
>>[Dbg]>>> 232792560
Also we can make factorization of all numbers in range into primes and remember the largest powers for every prime. In this case: 2:4; 3:2; 5:1; 7:1; 11:1; 13:1; 17:1; 19:1 and multiply these powers. More complex code (but this way might be useful sometimes)
232792560 = 16 * 9 * 5 * 7 * 11 * 13 * 17 * 19
Hope this is what you are looking:
for (int i = 2; i < Integer.MAX_VALUE; i++) {
for (int j = 2; j <= 20; j++) {
if (i % j == 0) {
System.out.println("i : "+i+" j : "+j);
break;
}
}
}
Here is the code when I haven't stored in a list. This gets what I want to display in different textfields but I want it to be shorter so I want to loop it.
//"answerStoration.retrieveDataChoices(i,TB)" is a function from other class that returns an arraylist;
quizAnswer1store.setText(answerStoration.retrieveDataChoices(1,TB).get(0));
quizAnswer2store.setText(answerStoration.retrieveDataChoices(1,TB).get(1));
quizAnswer3store.setText(answerStoration.retrieveDataChoices(1,TB).get(2));
quizAnswer4store.setText(answerStoration.retrieveDataChoices(1,TB).get(3));
quizAnswer1store2.setText(answerStoration.retrieveDataChoices(2,TB).get(0));
quizAnswer2store2.setText(answerStoration.retrieveDataChoices(2,TB).get(1));
quizAnswer3store2.setText(answerStoration.retrieveDataChoices(2,TB).get(2));
quizAnswer4store2.setText(answerStoration.retrieveDataChoices(2,TB).get(3));
quizAnswer1store3.setText(answerStoration.retrieveDataChoices(3,TB).get(0));
quizAnswer2store3.setText(answerStoration.retrieveDataChoices(3,TB).get(1));
quizAnswer3store3.setText(answerStoration.retrieveDataChoices(3,TB).get(2));
quizAnswer4store3.setText(answerStoration.retrieveDataChoices(3,TB).get(3));
I stored it in a List "quizAnswerSTORE" and I tried to loop but doesnt work.
int k = 0;
for(int i = 0; i<quizAnswerSTORE.size(); i++){
for(int j = 1; j < 11; j++){
while(k<4){
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
}
}
}
The expected result is to diplay different values from a database in different 40 txtfields. Because each time the loop values increments, it rolls through my database with different values. J variable represents the id in my database. And the K is an index in the values taken in the arrayList returned by retrieveDataAnswers function from a four columned database.
There you go. I hope you can solve this.
You can use mod to control maximun int values, for example i % 10 can't take values more than 10.
Example:
public class Main {
public static void main(String[] args) {
int j = 1;
int k = 0;
for(int i = 0; i < 40; i++) {
System.out.println("quizAnswerSTORE"+i+".setText(answerStoration.retrieveDataChoices("+j+",TB).get("+k+"));");
k = (k + 1)%4;
if( k == 0) {
j = (j+1) % 11;
}
}
}
}
output:
quizAnswerSTORE0.setText(answerStoration.retrieveDataChoices(1,TB).get(0));
quizAnswerSTORE1.setText(answerStoration.retrieveDataChoices(1,TB).get(1));
quizAnswerSTORE2.setText(answerStoration.retrieveDataChoices(1,TB).get(2));
quizAnswerSTORE3.setText(answerStoration.retrieveDataChoices(1,TB).get(3));
quizAnswerSTORE4.setText(answerStoration.retrieveDataChoices(2,TB).get(0));
quizAnswerSTORE5.setText(answerStoration.retrieveDataChoices(2,TB).get(1));
quizAnswerSTORE6.setText(answerStoration.retrieveDataChoices(2,TB).get(2));
quizAnswerSTORE7.setText(answerStoration.retrieveDataChoices(2,TB).get(3));
quizAnswerSTORE8.setText(answerStoration.retrieveDataChoices(3,TB).get(0));
quizAnswerSTORE9.setText(answerStoration.retrieveDataChoices(3,TB).get(1));
quizAnswerSTORE10.setText(answerStoration.retrieveDataChoices(3,TB).get(2));
quizAnswerSTORE11.setText(answerStoration.retrieveDataChoices(3,TB).get(3));
...
quizAnswerSTORE38.setText(answerStoration.retrieveDataChoices(10,TB).get(2));
quizAnswerSTORE39.setText(answerStoration.retrieveDataChoices(10,TB).get(3));
Try to be consistent with your indentation and line up closing brackets '}' with their corresponding statement.
The first problem I see with this code is that k is never incremented inside the while loop so it will always have the same value and loop forever. The second problem I see is that k is not reset after the while loop so when it goes through the loop the first time (and is correctly incremented) it will stay at a value of 4 and the loop will be skipped every time after that.
I'm not sure what you're trying to achieve (I could use some more information or a sample output) but to begin with you can correct the loop error by changing the while loop to a for loop like so.
for (int i = 0; i < quizAnswerSTORE.size(); i++) {
for (int j = 1; j < 11; j++) {
for (int k = 0; k < 4; k++) {
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
}
}
}
Alternatively, if you wanted to keep the while loop, you could so it like so.
for (int i = 0; i < quizAnswerSTORE.size(); i++) {
for (int j = 1; j < 11; j++) {
int k = 0; // Set k inside the 2nd loop and it will reset to 0 after the while loop
while(k < 4) {
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
k++; // Shorthand for k += 1 which is shorthand for k = k + 1
}
}
}
public static int[][] solve(int[][] input){
for (int i = 0; i < 9*9; i++){
if(input[i / 9][i % 9] != 0){
continue;
}
for (int j = 1; j <= 9; j++){
if(validNumber(input, i / 9, i % 9, j)){
input[i / 9][i % 9] = j;
solve(input);
}
}
}
return input;
}
This method should solve a (solvable) sudoku puzzle via backtracking regardless of the initial situation. It works like this:
Given a sudoku puzzle it iterates from the upper left corner over each row to the lower right corner of the 2D array. When there is already a number, it gets skipped. When there is a zero (empty field) it calculates possible values via the validNumber method. The first valid number (from 1 to 9) is put in the field and the method goes to the next field.
In this algorithm the method does not now whether or not a valid number will eventually render the puzzle unsolvable.
I want to alter it like this:
At the end, when the method finishes iterating through the whole 2d array, every entry of the array gets tested if it is a zero or not.
If there is even one zero the whole algorithm must go to the place where the very first "valid" number was put in. Now, the next "valid" number is put in and so on until there are no zeroes at the end of the algorithm.
I have some troubles implementing this thought. It seems to me there must be an other for loop somewhere, or something like a goto statement, but I don't know where to put it.
Any advice?
I implemented a Sudoku solver once before. It was a bit more complicated than what you had, but solved the game in a blink. :)
What you are attempting to do is solve Sudoku by "Brute Force" and using (tail) recursion. That means you are attempting to solve the board by iterating over all 981 possible combinations. 9 to the power of 81 is... well it's a big number. And so your approach will take eternity, but you'll run out of stack space from the tail recursion much sooner.
When I implemented Sudoko, it was more straight up. It kept a 9x9 array of "items", where each item was the value in the square, and an array of 9 booleans representing candidates (true == viable, false == eliminated). And then it just did a non-recursive loop of solving the board.
The main loop would start with the simple process of finding squares with only 1 remaining candidate. Then the next step would do simple candidate elimination based on values already assigned. Then it would work its way into more complicated elimination techniques such as X-Wing.
Your algorithm does not actually backtrack. It moves forward if it can, but it never moves backwards when it realizes it's stuck in a corner. This is because it never returns any knowledge up the stack, and it never resets squares. Unless you get really lucky, your code will get the game board into a cornered state, and then print out that cornered state. To backtrack, you need to reset the last square you set (the one that got you cornered) to zero, so your algorithm will know to keep trying other things.
For understanding backtracking, I highly recommend a book called The Algorithm Design Manual by Steven Skiena. I read it when I was preparing for SWE interviews, and it really improved my knowledge of backtracking, complexity, and graph search. The second half of the book is a catalog of 75 classic algorithmic problems, and Sudoku is one of them! He has an interesting analysis of optimizations you can make to prune the search tree and solve very hard puzzle boards. Below is some code I wrote a long time ago after reading this chapter (probably not that high quality by my current standards, but it works). I just read through it really quickly and added the solveSmart boolean in the solve method which allows you to turn one of those optimizations on or off, which results in a pretty big time savings when solving a "hard" class Sudoku board (one with only 17 squares filled in to start with).
public class Sudoku {
static class RowCol {
int row;
int col;
RowCol(int r, int c) {
row = r;
col = c;
}
}
static int numSquaresFilled;
static int[][] board = new int[9][9];
static void printBoard() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(" " + (board[i][j] == 0 ? " " : board[i][j]) + " ");
if (j % 3 == 2 && j < 8)
System.out.print("|");
}
System.out.println();
if (i % 3 == 2 && i < 8)
System.out.println("---------|---------|---------");
}
System.out.println();
}
static boolean isEntireBoardValid() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (!isBoardValid(i, j)) {
return false;
}
}
}
return true;
}
static boolean isRowValid(int row) {
int[] count = new int[9];
for (int col = 0; col < 9; col++) {
int n = board[row][col] - 1;
if (n == -1)
continue;
count[n]++;
if (count[n] > 1)
return false;
}
return true;
}
static boolean isColValid(int col) {
int[] count = new int[9];
for (int row = 0; row < 9; row++) {
int n = board[row][col] - 1;
if (n == -1)
continue;
count[n]++;
if (count[n] > 1)
return false;
}
return true;
}
static boolean isSquareValid(int row, int col) {
int r = (row / 3) * 3;
int c = (col / 3) * 3;
int[] count = new int[9];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int n = board[r + i][c + j] - 1;
if (n == -1)
continue;
count[n]++;
if (count[n] > 1)
return false;
}
}
return true;
}
static boolean isBoardValid(int row, int col) {
return (isRowValid(row) && isColValid(col) && isSquareValid(row, col));
}
static RowCol getOpenSpaceFirstFound() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == 0) {
return new RowCol(i, j);
}
}
}
return new RowCol(0, 0);
}
static RowCol getOpenSpaceMostConstrained() {
int r = 0, c = 0, max = 0;
int[] rowCounts = new int[9];
int[] colCounts = new int[9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != 0)
rowCounts[i]++;
if (board[j][i] != 0)
colCounts[i]++;
}
}
int[][] squareCounts = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int count = 0;
for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++) {
if (board[(i * 3) + m][(j * 3) + n] != 0)
count++;
}
}
squareCounts[i][j] = count;
}
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == 0) {
if (rowCounts[i] > max) {
max = rowCounts[i];
r = i;
c = j;
}
if (colCounts[j] > max) {
max = rowCounts[j];
r = i;
c = j;
}
}
}
}
return new RowCol(r, c);
}
static boolean solve() {
if (81 == numSquaresFilled) {
return true;
}
boolean solveSmart = true;
RowCol rc = solveSmart ? getOpenSpaceMostConstrained() : getOpenSpaceFirstFound();
int r = rc.row;
int c = rc.col;
for (int i = 1; i <= 9; i++) {
numSquaresFilled++;
board[r][c] = i;
if (isBoardValid(r, c)) {
if (solve()) {
return true;
}
}
board[r][c] = 0;
numSquaresFilled--;
}
return false;
}
public static void main(String[] args) {
// initialize board to a HARD puzzle
board[0][7] = 1;
board[0][8] = 2;
board[1][4] = 3;
board[1][5] = 5;
board[2][3] = 6;
board[2][7] = 7;
board[3][0] = 7;
board[3][6] = 3;
board[4][3] = 4;
board[4][6] = 8;
board[5][0] = 1;
board[6][3] = 1;
board[6][4] = 2;
board[7][1] = 8;
board[7][7] = 4;
board[8][1] = 5;
board[8][6] = 6;
numSquaresFilled = 17;
printBoard();
long start = System.currentTimeMillis();
solve();
long end = System.currentTimeMillis();
System.out.println("Solving took " + (end - start) + "ms.\n");
printBoard();
}
}
Eventually validNumber() method will not return any number because there is no possibilities left that means one of the previous choices was incorrect. Just imagine that the algorithm is started with the empty grid (obviously this puzzle is solvable1).
The solution is to keep tree of possible choices and if some choices are incorrect, then just remove them from the tree and use the next available choice (or step back on a higher level of the tree, if there is no choice left in this branch). This method should find a solution if any. (Actually this is how I implemented my sudoku solver some time ago.)
1 IMHO there are 3 different kinds of sudoku:
"true" correct sudoku that has a single unique complete solution;
ambiguous sudoku that has multiple distinct complete solutions, e.g. a puzzle with only 7 different numbers, so it has at least two distinct solutions that differ by swapping 8th and 9th numbers;
incorrect sudoku that has no complete solution, e.g. with a row with two or more occurrences of the same number.
With this definition, a solver algorithm should either:
prove that there is no solution;
return complete solution that satisfies the initial grid.
In the case of a "true" sudoku the result is a "true" solution by definition. In the case of an ambiguous sudoku the result can be different depending on the algorithm. An empty grid is the ultimate example of ambiguous sudoku.
everyone!I have a java app that shows all the prime numbers from 2 to a given number(user input).How can I print out just the last number, the biggest one I mean, from the given range?
For example:if the user input is 12,the compiler prints only 11,not 2,3,5,7,11.
Here is the code:
package sieve_eratos;
import java.util.Scanner;
public class Sieve_Eratos {
public static void main(String[] args) {
// get the ceiling on our prime numbers
int N;
Scanner sc = new Scanner(System.in);
System.out.print("enter the prime number ceiling: ");
N = sc.nextInt();
sc.close();
int k = 0;
// init numbers array, where true denotes primality
boolean[] isPrime = new boolean[N];
// init possible primes
isPrime[0] = false; // 1 is not prime
for (int i = 1; i < N; i++) {
isPrime[i] = true;
k = k + 1;
}
// check every number >= 2 for primality
for (int i = 2; i <= N; i++) {
// i is prime if it hasn't been "crossed off" yet
if (isPrime[i - 1]) {
// print out the prime number
System.out.println(i);
// "cross off" all the subsequent multiples of i
//for (int j = 2*i; j <= N; j += i) {
for (int j = i * i; j <= N; j += i) { // more efficient
isPrime[j - 1] = false;
}
}
}
}
}
I was thinking about creating another integer array and then calling the last element(which will be the last number stored),but I have no idea how to do this.
Thank you in advance!
Use NavigableSet.lower. Take a look at following example
Integer primeValues[]={2,3,5,7,11};//Here store all primes
NavigableSet<Integer> primeCollec=new TreeSet<>();
primeCollec.addAll(Arrays.asList(primeValues));
//Add all range prime into NavigableSet
int input=12;// Get the user input here
int output=primeCollec.lower(input);// Here is the desired output based on input
System.out.println(output);
Since the numbers are consecutive numbers (from 1 to N), we can check the Prime number flags (in your code, it is boolean[] isPrime )from biggest index.
If it is true, then the sum of its index and 1 (index+1) will be the ceiling prime we want.
Code is as follows:
public static int populateCeilingPrime(boolean[] flags)
{
int len = flags.length;
for(int i= len -1;i>=0;i--)
{
if(flags[i])
{
return i+1;
}
}
return 0;
}
so you just need to call this method above to populate the ceiling prime, using the following code at the end of main method.
System.out.printf("The ceiling prime is %d ", populateCeilingPrime(isPrime));
Instead of printing the prime, you could make a check if the number you want to print is larger than some earlier number you wanted to print and then if it is prime, and larger, you save that prime as the biggest so far. Once you are done with your sieveing process, that saved prime should be what you want.
Like so:
int maxPrime = 0;
for (int i = 2; i <= N; i++) {
// i is prime if it hasn't been "crossed off" yet
if (isPrime[i - 1]) {
if(i > maxPrime) {
maxPrime = i;
}
// "cross off" all the subsequent multiples of i
//for (int j = 2*i; j <= N; j += i) {
for (int j = i * i; j <= N; j += i) { // more efficient
isPrime[j - 1] = false;
}
}
}
System.out.println(maxPrime);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have been given a challenge to do witH Java and one of the questions I keep getting the wrong answer the question is:
What is the sum of all of the palindromic numbers that are the products of two 2-digit or 1-digit numbers?
Edit:
So I basically need code that will work out the sum of all palindromes who can be made from 2 numbers either 2-digit or 1-digit.
package projects;
import java.util.ArrayList;
public class Project3 {
public static void main(String[] args) {
new Project3();
}
public Project3(){
ArrayList<Integer> numbers = new ArrayList<Integer>();
//generate 1-9
for(int i = 1; i < 10; i++){
numbers.add(i);
}
//generate 11-99
for(int i = 10; i < 100; i+=10){
numbers.add(i + (i / 10));
}
//generate 100-999
for(int i = 100; i < 1000; i+=100){
for(int j = 1; j < 10; j++){
numbers.add(i + (j*10) + (i / 100));
}
}
//generate 1000 - 9999
for(int i = 1000; i < 10000; i+=1000){
for(int j = 1; j < 10; j++){
numbers.add(i + (j * 100) + (j * 10) + (i / 1000));
}
}
boolean product = false;
for(int i = 0; i < numbers.size(); i++){
product = false;
for(int j = 99; j >= 1; j--){
if(numbers.get(i).intValue() % j == 0){
product = true;
break;
}
}
if(product == false){
numbers.remove(i);
}
}
int total = 0;
for(int i = 0; i < numbers.size(); i++){
total += numbers.get(i);
System.out.println(numbers.get(i) + "\t\t" + total);
}
System.out.println(total);
}
public String reverse(String thing){
String reversed = "";
char[] array = thing.toCharArray();
for(int x = thing.length() - 1; x >= 0; x--){
reversed += array[x];
}
return reversed;
}
}
Edit:
I am trying to ask what/where my program is going wrong and what I could do to get a program that will give me th right answer.
Your logic goes wrong when you are checking for divisibility in the following loop:
for(int j = 99; j >= 1; j--){
if(numbers.get(i).intValue() % j == 0){
product = true;
break;
}
Here you are just checking if the palindrome is divisible by a number between 1-99 but you are not worried about the other factor of the palindrome.
Example:
Let the palindrome be 2222.
When checking for its divisibility (inside 'j' loop), it is divisible by 22 and hence you are including it in the list, where as the other factor is 101 which is not a 2-digit/1-digit number.
You have to eliminate all such cases.
So instead of following this algorithm, it is better if you follow the algorithm in a reverse way as mentioned by few users above.
You try to create all the palindromic numbers and then check whether they are a product of some numbers. Instead, try it the other way around. You already have a reverse function, so just do this:
int counter = 0;
for (int i = 0; i < 100; i++) {
for (int k = i; k < 100; k++) {
String s = String.valueOf(i * k);
if (s.equals(reverse(s))) counter++;
}
}
Just one potential problem:
for(int i = 0; i < numbers.size(); i++){
...
if(product == false){
numbers.remove(i);
}
}
This might skip numbers. Consider the list N,P,* (where N is a non-product palidrome, P is a product palindrome and * is any palindrome). i is 0 and since N is a non-product palidrome it will be removed and your list now is P,*. Now i will be increased to 1 and thus the i-th element is *. P will be skipped - ouch.
To fix that, you might collect the palindromes into another set/list/collection and leave numbers unchanged.
Alternatively iterate backwards, i.e. for( i = numbers.size(); i >= 0; i--).
A thirds option would be to use an iterator, e.g. for( Iterator<Integer> itr = numbers.iterator(); itr.hasNext(); ) { ... } and then itr.next() and itr.remove().
Btw, you might want to use for a foreach loop whenever the value of i is not relevant, e.g. for(Integer number : numbers )
Edit: changed the example from 10,11,12 to 65,66,67 to reduce confusion. Please note that it's still an example and not necessarily based on your actual data.
Edit 2: I changed the example to something more abstract to avoid (or generate? ;) ) further confusion. Since I can't currently think of a sequence of a non-product palindrome followed by a product palindrome (product here means matching the requirement of being a product of 2 one- or two-digit numbers), I changed it to N,P,*.
I'll restate the point of my potential bug answer: when you iterate forward using indices and remove elements at the current or a lower index, you would skip elements, so don't do that unless you want that exact behavior.