I am still very new to Java and I am struggling a bit trying to understand why does my code only return "false" when modulo is not equal to 0, ignoring the two other cases, so when divisor is 0 and when the array is empty.
In case of divisor = 0, I get java.lang.ArithmeticException: divide by zero
For some reason empty array IS divisible by 0, how could that be?
Any help highly appreciated, thanks!
public boolean Divisible(ArrayList<Integer> array1, int divisor) {
int i;
int modulo;
boolean isDiv=true;
for(i=0; i<arr.size(); i++){
modulo=((arr.get(i)%divisor));
i++;
if(modulo!=0 || divisor==0 || arr.isEmpty())
{
isDiv= false;
break;
}
}
return isDiv;
}
Before you do anything check for an empty List or a 0 divisor.
if(divisor==0||array1.isEmpty()){
return false;
}
Then you can check the list.
for(Integer i: array1){
if(i%divisor!=0){
return false;
}
}
Finally.
return true;
The main problem is that you're executing the OR check inside the for loop, but if the for loop iterates 0 times the condition is never checked, so the problem you're experiencing.
Here is a modified version of your function, where I moved the check conditions outside the for loop:
public boolean Divisible(ArrayList<Integer> array1, int divisor)
{
int i;
int modulo;
boolean isDiv = true;
if(array1.isEmpty()) // Check array1.isEmpty() outside for loop.
{
isDiv = false;
}
else if(divisor == 0) // Check divisor outside for loop.
{
isDiv = false;
}
else
{
for(i = 0; i < arr.size(); i++)
{
modulo = (arr.get(i) % divisor);
// i++; i is already increased by for instruction.
if(modulo!=0 /*|| divisor==0 || arr.isEmpty()*/) // Only modulo must be checked here.
{
isDiv= false;
break;
}
}
}
return isDiv;
}
Related
what i'm trying to do is to check if 2 is before 4 in a array i used a for loop and condition check and i see that i'm going wrong in my first condition check. i want to make it so that if two is not in the loop it just breaks and if it sees that four is before it breaks as well.
i put the print statement to see where i was going wrong and it seems to if(array[i] == two and it goes to the else and breaks. i also read that you can do it with another array but that sound off so i also wanted to ask if that was possible.
public static void main(String[] args) {
int[] check = {2, 3, 4, 2, 6};
System.out.println(universe42(check));
}
private static boolean universe42(int[]array){
boolean check1 = false;
boolean check2 = false;
int two = 2;
int four = 4;
for(int i=0; i< array.length; i++) {
if (array[i] == two) {
check1 = true;
System.out.println("check1");
}
else {
System.out.println("check-------");
break;
}
if (array[i]== four){
check2=true;
}
}
if(check1==true && check2== true){
return true;
}
return false;
}
}
You're breaking the loop execution if array[i]==two is false, and it eventually always is, because at position 1 you have a 3, and you always run the first check.
You need to remove the break of the else.
You need to break when you find a 4, not when you don't find a 2. Something like this:
boolean foundTwo = false;
for (int x : array) {
if (x == 2) {
foundTwo = true;
} else if (x == 4) {
break;
}
}
return foundTwo;
If you want to make sure there's both a 2 and a 4, in the correct order, just return on 4 instead of breaking, and default to false otherwise:
boolean foundTwo = false;
for (int x : array) {
if (x == 2) {
foundTwo = true;
} else if (x == 4) {
return foundTwo;
}
}
return false;
The task is to implement a program which counts how many different Sums of Primes there are for a given number sumtoBreak.
The Method primeSum should subtract all possible primes currprime from the number sumtoBreak until the sumtoBreak becomes zero and then return (in sum) a one for each possibilty. To account for all possibilities, in each recession step, it calls itself
with sumtoBreak - currprime plus
calls itself with the nextPrime.
My Problem is that java won't return anything unless the sumtoBreak is zero right at the beginning.
Would be glad for any advice!
Here's the code (I know that the parenthesis in the code with the nested if statements are redundant, but I just wanted to make sure, that's not the problem):
Here's the fixed code:
public class PrimeSum {
public static boolean isPrime(int primecandidate) {
int count = 0;
for (int i = 2; i <= primecandidate / 2; i++) {
if (primecandidate % i == 0)
count++;
}
if (count == 0)
return true;
else
return false;
}
public static int nextPrime(int currprime) {
int j = currprime + 1;
while (!isPrime(j))
j++;
return j;
}
public static int primeSum(int sumtoBreak, int currprime) {
if (sumtoBreak == 0) {
return 1;
} else {
if (sumtoBreak < 0 || currprime > sumtoBreak) {
return 0;
} else {
return primeSum(sumtoBreak, nextPrime(currprime)) + primeSum(sumtoBreak - currprime, currprime);
}
}
}
public static void main(String[] args) {
System.out.println(primeSum(Integer.parseInt(args[0]), 2));
}
}
This doesn't answer your question, but corrects an error in your isPrime Method and computes the result much faster:
private static boolean isPrime(final int primecandidate) {
if ( primecandidate < 2) { // 0 & 1 are NOT Prime
return false;
}
if ((primecandidate & 0x1) == 0) { // Even is NOT Prime...
return primecandidate == 2; // ...except for 2 (and 0).
}
for (int i = 2, iMax = (int) Math.sqrt(primecandidate); i <= iMax; i++) {
if (primecandidate % i == 0) {
return false;
}
}
return true;
}
Note the following:
the final argument primecandidate is marked final
it corrects the result for 0 & 1 to false
the method is marked private
the iMax is Sqrt(primecandidate) & not primecandidate / 2
iMax is calculated once, instead of every iteration
I use a strategy I call "if you're done, be done."
Meaning: don't set a flag (in your case count), just get out!
Please note also, there is an apache commons Math3 function...
org.apache.commons.math3.primes.Primes.isPrime(j)
It is significantly slower for smallish values (<= Short.MAX_VALUE)
It is somewhat faster for largeish values (ca. Integer.MAX_VALUE)
There is also a BigInteger.isProbablePrime(...) function, but my Benchmark suggests it is rather slow.
I hope this helps a little?
Some things you might have missed:
in a function, a return statement terminates (break) the function immediatly. So in
if(...) { return ...; }
else {...}
→ else is redundant, as if the condition is true, the function is already terminated (break)
Something like a==0 has a boolean value (true or false). So
if(count==0) { return false; }
else { return true;}
can be shortened to return count!=0;
I recommend to always use braces, because something like if(i==0) ++i; break;, means if(i==0) {++i;}. break; will be called in any case.
public static boolean
isPrime(int n)
{
if(n==0 || n==1) { return false; }
for(int i= 2; i <= n/2; ++i)
{
if(n%i == 0) { return false; } //we know, n is not a prime,
//so function can break here
}
return true; //since for all values of i, the function did not break,
//n is a prime
}
I wish you a lot of motivation to code for the future!
This is the question : An array is sorted (in ascending order) if each element of the array is less than or equal to the next element.
Write a boolean-valued method named isSorted that accepts an integer array, and the number of elements in the array and returns whether the array is sorted.
Before showing the code : my logic is that an if else-if and else statement should first determine if the size of the array is 0,1,or 2. This is because when the size equals 1 or 2, the program must break. When the size is larger than 2, the program should check arr[size-1] > arr[size-2] and then call the method again with size decremented if that is true and just return false if it is untrue. When I ran that program, the following 2 tests failed : [1,3,2,4] and [2,1,2,3,4]. Because of this I specified that when the size is equal to 2, the method returns false if arr[0] > arr[1] however it didn't work. What am I doing wrong? I don't want to just look up the answer because I am studying for a test so I am sorry if there are repeated answers.
I know the loop is better I just wanted to study recursion
public boolean isSorted(int[] arr, int size) {
if(size == 0 || size == 1) {
return true;
} else if (size == 2) { //this is the part I don't get.
if (arr[0] > arr[1]) {
return false;
} else {
isSorted(arr,size-1);
return true;
}
} else {
if (arr[size-1] < arr[size-2]) {
return false;
} else {
isSorted(arr, size-1);
return true;
}
}
}
Recursion is not good way to solve this problem. What if your array will be very big and you could get StackOverflowError. Why not to use simple if operator:
public static boolean isSorted(int[] arr, int size) {
if (arr.length >= 2)
for (int i = 1; i < arr.length; i++)
if (arr[i - 1] > arr[i])
return false;
return true;
}
You need return the result from isSorted, for example, change:
isSorted(arr, size-1);
return true;
to
return isSorted(arr, size-1);
And, the case else if (size == 2) is redundant. size 2 should have the same logic with size 3, 4, 5, ...
Complete code:
public boolean isSorted(int[] arr, int size) {
if (size == 0 || size == 1) {
return true;
} else {
if (arr[size - 1] < arr[size - 2]) {
return false;
} else {
return isSorted(arr, size - 1);
}
}
}
I have two methods to find out prime number in java method - 2 working fine but getting wrong output from method one, can any help me where i did wrong in logic. Thanks in advance
My entire code
package prepare;
import java.util.Scanner;
public class Squar {
//Method - 1 to find prime number
boolean isPrime(int num){
int exp = (int)Math.sqrt(num);
for(int i=2;i<exp;i++){
if(exp%2==0){
return false;
}
}return true;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
Squar s = new Squar();
System.out.println("From M1 "+s.isPrime(num));
scan.close();
System.out.println("From M2 "+s.isPrimeNumber(num));
}
//Method - 2 to find prime number
public boolean isPrimeNumber(int number) {
if(number == 1){
return false;
}
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
for input : 63 actual out put would be false in prime number but getting
different output from method one
output
63
From M1 true
From M2 false
In isPrime() method, Shouldn't you be checking num % i == 0 rather than exp % 2 == 0?
Change isPrime function like this.
boolean isPrime(int num) {
int exp = (int) Math.sqrt(num);
for (int i = 2; i < exp; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
Because in if condition you are checking exp%2 == 0 . But this statement does not change when iterating on i < exp. So this logic should be on with num % i == 0
Have a look at this line of your code
if(exp%2==0){
it should be num % i
Well I think the culprit is
if(exp%2==0){
and it is causing a problem while iterating i<exp.So you may want to tweak it to
num%i==0
I have tried to give a few other approaches to this issue.
I hope that would be helpful.
I think there is a reason that tempted you to use
(int)Math.sqrt(num);
I have tried to elaborate it below.
Consider below 3 approaches.
All of them are correct but the first 2 approaches have some drawbacks.
Approach 1
boolean isPrime(int num) {
for(int i=2;i<num;i++) {
if(num%i==0)
return false;
}
return true;
}
We have a scope to make it faster.
Consider that if 2 divides some integer n, then (n/2) divides n as well.
This tells us we don't have to try out all integers from 2 to n.
Now we can modify our algorithm:
Approach 2
//checks whether an int is prime or not.
boolean isPrime(int num) {
for(int i=2;2*i<num;i++) {
if(num%i==0)
return false;
}
return true;
}
Finally, we know 2 is the "oddest" prime - it happens to be the only even prime number.
Because of this, we need only check 2 separately, then traverse odd numbers up to the square root of n.
I think this might have tempted you to use (int)Math.sqrt(num);
Approach 3
//checks whether an int is prime or not.
boolean isPrime(int num) {
//check if num is a multiple of 2
if (num%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=num;i+=2) {
if(num%i==0)
return false;
}
return true;
}
Hence, we've gone from checking every integer (up to n to find out that a number is prime) to just checking half of the integers up
to the square root.
Is it not an improvement, especially considering when numbers are large.
Well, your first algorithm is almost (replace %2 with %i) correct. I do not know the second algorithm, but i would definitely change it to this form:
public boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
I'm currently working on a program in which the user inputs a number, and the program will give you the number of prime numbers up to that number. Although there are no errors, the program always outputs the same number: 3. This is the code:
public static int Prime(int num){
boolean isPrime = true;
int count = 0;
for (int a = 2; a <=num; a++){
for (int i = 2; i <= a/2; i++){
if (a == 2 || a == 3 || a == 5){
isPrime = true;
}
else if (a % i == 0){
isPrime = false;
}
}
if (isPrime == true)
count++;
}
return count;
}
In your inner for loop, you are setting isPrime, but then you keep looping. Subsequent loops may set isPrime to false if a candidate divisor i doesn't divide cleanly. Only 2, 3, and 5, the 3 numbers in your first if condition, set it to true always, so you always get 3.
Instead, set isPrime to true at the beginning of the inner for loop, and break out of the inner for loop after each time you set isPrime. If the number is 2, 3, or 5, set to true and break so nothing can set it to false, so you can count it. If you found a factor, it's not prime, so set to false and break so nothing can set it to true and it's not counted.
Incidentally, your final if condition tests a boolean; it can be simplified to if (isPrime).
Your strategy is to test each number from 2 through num for primality by scanning for factors other than itself and 1. That's ok, albeit a bit simplisitic, but your implementation is seriously broken.
An approach involving scanning for factors implies that you start by guessing that the number being tested is prime, and then go looking for evidence that it isn't. You've missed the "guessing it's prime" part, which in your particular code would take the form of setting isPrime to true at the beginning of your outer loop.
Your code, on the other hand, never resets isPrime to true after testing the case of a == 5. That variable will be set to false when testing the case of a == 6, and will remain so for the duration. That is why you always get the result 3 for any input greater than 4.
If you properly reset isPrime in the outer loop then you can also remove the first part of the conditional in the inner loop, as it will be redundant. It is anyway never executed in the cases of a == 2 and a == 3 because the inner loop performs zero iterations in those cases.
Note also that it would be more efficient to break from the inner loop as soon as you determine that a is composite, and that you run more iterations of that loop than you need to do for primes (it would be sufficient to loop until i exceeds the square root of a; that is, until i * i > a).
Finally, note that this problem would be more efficiently implemented via the Seive of Eratosthenes (or one of the other prime number seives) as long as the numbers you want to test are not so large that the needed array would be prohibitively large.
I simplified your code by reducing number of operations which is needed to check if a is 2, 3, or 5.
public static int Prime(int num) {
int count = 0;
if (num >= 2) {
count++; // One optimization here
}
for (int a = 3; a <= num; a+=2) { // Another one here as we don't have any even number except 2 :D
boolean isPrime = true;
for (int i = 2; i <= a / 2; i++) {
if (a % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
count++;
}
}
return count;
}
#include <iostream>
using namespace std;
int numberOfPrimes(int num)
{
if(num==2)
return 1;
else if(num<2)
return 0;
int prime=1;
for(int i=3;i<=num;i++)
{
for(int j=2;j<=(i/2)+1;j++)
{
if(i%j==0)
break;
if(j==(i/2)+1)
prime++;
}
}
return prime;
}
package com.amit.primenumber;
public class PrimeNumber {
public static void main(String[] args) {
long number=23L;
String message=null;
PrimeNumber primeNumber = new PrimeNumber();
boolean result = primeNumber.primeNumber(number);
if(result){
message="a Prime Number";
}else{
message="Not a Prime Number";
}
System.out.println("The given "+number+" number is "+message);
}
public boolean primeNumber(long number){
for(long i=2;i<=number/2;i++){
if(number%i==0){
return false;
}
}
return true;
}
}
package basics;
public class CheckPrimeOrNot {
public void checkprimeNumber(int i){
int flag=0;
if(i>2){
for(int j = 2; j <= i/2; j++){
if(i%j == 0){
System.out.println("Given number is Not Prime");
flag=1;
break;
}
}
if(flag==0){
System.out.println("Given number is Prime");
}
} else{
System.out.println("Please enter a valid number");
}
}
public static void main(String[] args) {
CheckPrimeOrNot CheckNumber = new CheckPrimeOrNot();
CheckNumber.checkprimeNumber(11);
CheckNumber.checkprimeNumber(0);
CheckNumber.checkprimeNumber(250365);
CheckNumber.checkprimeNumber(1231);
}
}