I need to find the numbers in a series that meet criteria set up in two different methods.
I have tried moving the statement that appends the variable primepalindromes out of the for loop in the main method but that gives me a number a single number past the series of number I set to be checked.
public static void main(String[] args) {
boolean isPrime = true;
boolean isPalindrome = true;
String primepalindromes = "";
int j;
for (j = 1; j <= 100; j++) {
checkprime(isPrime, j);
if (isPrime = true) {
checkpalindrome(isPalindrome, j);
if (isPalindrome = true) {
primepalindromes = primepalindromes + j + " ";
}
}
}
System.out.println(primepalindromes);
}
private static boolean checkprime(boolean isPrime, int j) {
int temp = 0;
for (int i = 2; i <= j / 2; i++) {
temp = j % i;
if (temp == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
private static boolean checkpalindrome(boolean isPalindrome, int j) {
int r, sum = 0, temp;
temp = j;
while (j > 0) {
r = j % 10;
sum = (sum * 10) + r;
j = j / 10;
}
if (temp == sum) {
isPalindrome = false;
}
return isPalindrome;
}
The code is supposed to return all numbers in the set series that fit the criteria of the two methods but instead it just gives all of the numbers in that series.
The problem is in your 'if' statements :
if (isPrime = true) {
if (isPalindrome = true) {
The single "equals" sign is an assignment, and the value of that is the valuie being assigned - which in these cases is always true.
Change them to use double-equals operator :
if (isPrime == true) {
or, since these are boolean variable, it is better to simply use them directly :
if (isPrime) {
EDIT TO ADD:
Also, you are not assigning the result of calling the functions. In a function, Java does not change the value of primitive types passed in as arguments, which means when you have :
boolean checkprime(boolean isPrime, int j)
and call it with, say, :
checkprime(someIsPrimeVariable, j);
Assigning a value to isPrime does not change the value of the variable that the caller supplied (ie someIsPrimeVariable is not changed).
So discard the isPrime argument, and instead just use the return value, so :
isPrime = checkprime(int j);
So your code would become :
for (j = 1; j <= 100; j++) {
isPrime = checkprime(j);
if (isPrime) {
isPalindrome = checkpalindrome(j);
if (isPalindrome) {
primepalindromes = primepalindromes + j + " ";
}
}
}
Related
This is my block of code for determining if a number is prime or not which is really a simple problem. however, it does not pass the unit test and I have no idea why. I have tried different primitive variable types, but to no avail. It passes all the explicit test cases, so I have no idea which value of n it is not checking correctly of its prime status.
public static boolean isPrime(int n) {
boolean f = true;
if (n % 2 == 0) {
return false;
}
double sqrt = Math.sqrt(n);
for (int i = 3; i <= sqrt; i++) {
if (((n % i) == 0)) {
f = false;
break;
}
}
return f;
}
The unit test in question gives the result:
java.lang.AssertionError:
Expected :783904569
Actual :3149358104
And here is the unit test code
CRC32 check = new CRC32();
for(int k = 0; k < 10_000_000; k++) {
if(Primes.isPrime(k)) { check.update(k); }
}
assertEquals(783904569L, check.getValue());
}
I have tried everything reasonable including re writing the code differently, but it keeps giving the same answer.
Your isPime() has two mistakes:
isPrime(1) == true
isPrime(2) == false
The test passes if you add the following to the beginning of the method:
if (n == 1) return false;
if (n == 2) return true;
You can speed it up with Sieve of Eratosthenes.
static final int MAX_PRIMES = 10_000_000 + 1;
static final boolean[] PRIMES = new boolean[MAX_PRIMES];
static {
Arrays.fill(PRIMES, true);
PRIMES[0] = PRIMES[1] = false;
for (int i = 2, end = (int)Math.sqrt(MAX_PRIMES); i <= end; ++i)
for (int j = i + i; j < MAX_PRIMES; j += i)
PRIMES[j] = false;
}
public static boolean isPrime(int n) {
return PRIMES[n];
}
This question already has answers here:
Continue at first loop , inside the second loop
(7 answers)
Closed 1 year ago.
For this code kata I need to continue 2 for loops at the same time. How can I do that?
public class StringMerger {
public static boolean isMerge(String s, String part1, String part2) {
StringBuilder MergedWord = new StringBuilder("");
String Whole = part1+part2;
for(int j = 0; j < Whole.length(); j++){
for(int I = 0; I < part1.length(); I++){
if((Character.compare(s.charAt(j), part1.charAt(I)) == 0) && (j == I)){
MergedWord.append(s.charAt(I)+"");
continue;
}
else
break;
}
for(int i = 0; i < part2.length(); i++){
if((Character.compare(s.charAt(j), part2.charAt(i)) == 0) && (j == i)){
MergedWord.append(part2.charAt(i) + "");
continue;
}
else
break;
}
}
return s.equals(MergedWord.toString())? true : false;
}
}
I noticed when one of the for loops continue it only continues the internal loop, but labels would continue the upper loop and would be inefficient. Could I continue 2 for loops at the same time a.k.a continue the inner and upper loop in this nested for loop?
The task is to match each character in the target string, so you only need one loop, which iterates over the characters in the string. You do need two other loop variables to track how much of the two source strings have been used up.
My solution below is looping over three things at once: the target string and the two 'part' strings. The rate it moves over the 'part' strings isn't constant, but it does progress over them monotonically.
It wasn't clear to me whether the source strings could include extra characters not used in the target string. As the example didn't show any, I assumed not.
public class MergedStringChecker {
public static void main(String[] args) {
String target = "codewars";
String part1 = "cdw";
String part2 = "oears";
for (int i = 0, p1 = 0, p2 = 0; i < target.length(); ++i) {
if (p1 < part1.length() && target.charAt(i) == part1.charAt(p1)) {
++p1;
} else if (p2 < part2.length() && target.charAt(i) == part2.charAt(p2)) {
++p2;
} else {
throw new RuntimeException("No matching characters at index " + i);
}
}
}
}
The above solution is not Unicode safe if the string contains > 16 bit code points.
Try this.
public static boolean isMerge(String s, String part1, String part2) {
int length = s.length();
int length1 = part1.length();
int length2 = part2.length();
int i1 = 0, i2 = 0;
for (int i = 0; i < length; ++i)
if (i1 < length1 && s.charAt(i) == part1.charAt(i1))
++i1;
else if (i2 < length2 && s.charAt(i) == part2.charAt(i2))
++i2;
else
return false;
return i1 == length1 && i2 == length2;
}
public static void main(String[] args) throws IOException {
System.out.println(isMerge("codewars", "cdw", "oears"));
System.out.println(isMerge("codewars", "codewars", ""));
System.out.println(isMerge("codewars", "cdw", "oearsEXTRA"));
}
output:
true
true
false
you have an error on the first part loop you must append from the part not the s char
you don't need to chek the id of the part with the inital word (remove this check (j == I) and this one (j == i)
Use counter to avoid looping many times
Try this code :
public static boolean isMerge(String s, String part1, String part2) {
StringBuilder MergedWord = new StringBuilder("");
String Whole = part1+part2;
int counter1=0;
int counter2=0;
for(int w = 0; w < Whole.length(); w++){
for(int c1 = counter1; c1 < part1.length(); c1++){
if((s.charAt(w) == part1.charAt(c1)) ){
MergedWord.append(part1.charAt(c1)+"");
counter1++;
continue;
}
else
break;
}
for(int c2 = counter2; c2 < part2.length(); c2++){
if((s.charAt(w) == part2.charAt(c2)) ){
MergedWord.append(part2.charAt(c2) + "");
counter2++;
continue;
}
else
break;
}
}
return s.equals(MergedWord.toString())? true : false;
}
result isn't initialized, how to do it in this method?(to preserve the functionality of the code)
static int maxNumbers(int r, int s) {
int result;
int[] rk = new int[r];
for (int i = 0; i < rk.length; i++) {
if (s > 1) {
rk[i] = (s - 1) + 1;
s--;
} else if (s == 1) {
rk[i] = (s + 1) + 1;
s = 0;
} else {
rk[i] = 1;
}
}
for (int i = 0; i < rk.length; i++) {
result = rk[0] * 2 * rk[i++]*2;
}
return result;
}
For the integer primitive and regarding your example you can simply write int result = -1;.
Although you set your result variable in the 2nd for loop, the compiler cannot guarantee that this for loop actually loops and therefore the variable will be set.
So in the end you should check the result of the method.
My code in Java:
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Введите целое число: ");
int n = scanner.nextInt();
boolean isPrime = false;
for (int i = 2; i <= n; i++) {
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
} else {
isPrime = true;
}
}
if (isPrime) {
System.out.println(i);
}
}
}
}
But my teacher said that I should move the boolean variable into the loop. This will simplify the code.
But I do not understand how to do it.
What your teacher is saying is that this line:
boolean isPrime = false;
Needs to be moved into the loop where the comments are. You are clearly looking for all prime numbers between 2 and n. Your loop variable 'i' is the prime-number to test, and whether it is prime or not, needs to be initialized to false every time you start an iteration test.
for (int i = 2; i <= n; i++) {
// NEEDS TO BE RIGHT HERE -
boolean isPrime = true;
// You are finding Prime Numbers, and the outer-loop (loop-var 'i')
// Means the 'isPrime' needs to be re-initialized each time you start testing
// whether a certain number, i, is prime or not!
for (int j = 2; j < i; j++)
if (i % j == 0) { isPrime = false; break; }
// and this line needs to be removed completely.
// else { isPrime = true; }
if (isPrime) System.out.println(i);
}
I'm trying to make a while loop that iterates through every long number possible and add every prime number it encounters into an the primes array. Since the while loop is supposed to run until the length of primes is 200, I expect the primes array to be filled with the first 200 prime numbers. Instead I get all zeroes. I have successfully gotten 20 rows of 10 characters each with a space in between them. How may I get them to be the actual prime numbers though?
public class PrimeGenerator {
public static void main(String[] args) {
long primes[] = new long[200];
while (primes.length > 200){
for(long y = 2; y < Long.MAX_VALUE; y++) {
int primeCounter = 0;
if (isPrime(y) == true){
primes[primeCounter] = y;
primeCounter++;
}
}
}
for (int i = 0; i < 20; i++) {
int primeCounter = 0;
for(int p = 0; p < 10; p++) {
System.out.print(primes[primeCounter] + " ");
primeCounter++;
}
System.out.println();
}
}
public static boolean isPrime(long number) {
if (number % 2 == 0)
return false;
if (number == 2)
return true;
for(int x = 3; x*x <= number; x+=2) {
if (number%x == 0)
return false;
}
return true;
}
}
primes.length is always 200 so the while loop is never entered.
The while loop is useless. Just add a condition to the for loop that would exit when the entire array has been assigned. Also move the initialization of primeCounter to be outside the for loop. Otherwise all the primes will be assigned to primes[0].
long primes[] = new long[200];
int primeCounter = 0;
for(long y = 2; y < Long.MAX_VALUE && primeCounter < 200; y++) {
if (isPrime(y) == true){
primes[primeCounter] = y;
primeCounter++;
}
}
for (int i = 0; i < primes.length; i++) {
System.out.print(primes[i]);
if ((i+1) % 10 == 0)
System.out.println();
}
EDIT :
As Sweeper commented, you should also fix your isPrime method, since it returns false for 2 :
public static boolean isPrime(long number) {
if (number == 2)
return true;
if (number % 2 == 0)
return false;
for(int x = 3; x*x <= number; x+=2) {
if (number%x == 0)
return false;
}
return true;
}
this code down
long primes[] = new long[200];
while (primes.length > 200){
means
while (200 > 200){
or the same as
while (false){
so your loop is NEVER executed!
because you did:
while (primes.length > 200)
and the length of the array is always 200,you never get into the while loop , and the zero in the array are coming because when you create array of "long" it initialized him with zeros
Firstly, the length of an array doesn't change. So, when you are testing for primes.length > 200 this will always be false, and the loop is never even entered. Therefore all values in the array are left at the default value of 0.
For doing this I would doing something like the following:
int primeCounter = 0;
long current = 0L;
while(primeCounter < primes.length){
if(isPrime(current)){
primes[primeCounter] = current;
primeCounter++;
}
current++;
}
An array's length never changes. If you declared an array to have a length of 200, it will always have a length of 200. Because of this, your while loop is never executed, not even once.
There are a lot of other errors in the code, so I tried to create a solution with as few changes as possible:
public static void main(String[] args) {
int primeCounter = 0;
long nextPossiblePrime = 2;
long primes[] = new long[200];
while (primeCounter < 200) {
for (long y = nextPossiblePrime; y < Long.MAX_VALUE; y++) {
if (isPrime(y) == true) {
primes[primeCounter] = y;
primeCounter++;
nextPossiblePrime = y + 1;
break;
}
}
}
primeCounter = 0;
for (int i = 0; i < 20; i++) {
for (int p = 0; p < 10; p++) {
System.out.print(primes[primeCounter] + " ");
primeCounter++;
}
System.out.println();
}
}
public static boolean isPrime(long number) {
if (number == 2 || number == 3)
return true;
if (number % 2 == 0)
return false;
for (int x = 3; x * x <= number; x += 2) {
if (number % x == 0)
return false;
}
return true;
}
The first problem is that you created two primeCounters, which is not needed. I removed the extra one and moved the scope of it to the scope of the method. The next problem is that your first for loop doesn't remember the prime number that it is on and it doesn't stop when it has found one so it will keep adding the 200th prime to the array. I fixed this by adding a nextPossiblePrime variable that stores what number should the program check next. The last problem is that your isPrime method is written incorrectly. I fixed it for you!
Here's another (cleaner) solution, which still uses a while loop:
public static void main(String[] args) {
ArrayList<Long> primes = new ArrayList<>();
long y = 2;
while (y < Long.MAX_VALUE && primes.size() < 200) {
if (isPrime(y) == true){
primes.add(y);
}
y++;
}
for (int i = 0; i < primes.size(); i++) {
System.out.print(primes.get(i) + " ");
if ((i+1) % 10 == 0)
System.out.println();
}
}
public static boolean isPrime(long number) {
if (number == 2 || number == 3)
return true;
if (number % 2 == 0)
return false;
for (int x = 3; x * x <= number; x += 2) {
if (number % x == 0)
return false;
}
return true;
}