I need to return -1 if one of this two conditions: biggerThanK(array[i], k), or prim(array[i]) return false. I tried to put an else { smallest = -1; } but if I input values that respect both conditions it still displays -1.
import java.util.Scanner;
public class Main {
public static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int n = scanner.nextInt();
int k = scanner.nextInt();
int[] array = new int[n];
for (int i = 0; i < array.length; i++) {
array[i] = scanner.nextInt();
}
for (int i = 0; i < array.length; i++) {
if (biggerThanK(array[i], k) && prim(array[i])) {
if (array[i] < smallest) {
smallest = array[i];
}
}
}
System.out.println(smallest);
}
public static boolean biggerThanK(int number, int k) {
if (number >= k) {
return true;
} else {
return false;
}
}
public static boolean prim(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
} return true;
}
}
You should put this in a function.
If only one of the conditions needs to be false, I would use an architecture like this :
if(condition 1)
if(condition 2)
//update smallest
else
return -1
else
return -1
Related
public static int maxIceCream(int[][] costs, int coins) {
Arrays.sort(costs);
boolean found = false;
for (int i = 0; i < costs.length; ++i) {
if (coins != costs[i]) {
coins -= costs[i];
found = true;
break;
} else {
return i;
}
}
return costs.length;
}
compare to integer and integer array
You are getting the error message because "costs" is a 2D matrix and "coins" is an integer.
So, you can't compare an integer(int) to array of integer(int[]).
Try looping two times over the "costs" to compare to all the values
public static int maxIceCream(int[][] costs, int coins) {
Arrays.sort(costs);
boolean found = false;
for (int i = 0; i < costs.length; ++i) {
for (int j = 0; j < costs[i].length; ++j) {
if (coins != costs[i][j]) {
coins -= costs[i][j];
found = true;
break;
} else {
return i;
}
}
}
return costs.length;
}
I am writing a merge sort algorithm that will sort an ArrayList then search the sorted list to see if a value match's two numbers in the list. I am getting an error after the while loop in the merge method. The error is ConcurrentModificationException but I am not too sure why. Ideally keeping the code as similar as possible.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Value {
static List<Integer> test = new ArrayList<>();
static public void main(String[] args) {
System.out.println("Generate Array");
setUpArray(test);
System.out.println(Arrays.asList(test));
Scanner scan = new Scanner(System.in);
System.out.println("Please enter Value");
int value = scan.nextInt();
scan.close();
mergeSort(test);
boolean b = findValue(test,value);
if(b){
System.out.println("Found");
}else{
System.out.println("Couldn't Find");
}
}
public static void mergeSort(List<Integer> input) {
int inputLength = input.size();
int mid = inputLength / 2;
if (inputLength < 2) {
return;
}
List<Integer> left = input.subList(0, mid);
List<Integer> right = input.subList(mid, inputLength);
mergeSort(left);
mergeSort(right);
merge(input, left, right);
}
public static void merge(List<Integer> input, List<Integer> left, List<Integer> right) {
int i = 0, j = 0, k = 0;
while (i < left.size() && j < right.size()) {
if (left.get(i) <= right.get(j)) {
input.add(k, left.get(i));
i++;
} else {
input.add(k, right.get(j));
j++;
}
k++;
}
while (i < left.size()) {
input.add(k, left.get(i));
i++;
k++;
}
while (j < right.size()) {
input.add(k, right.get(j));
j++;
k++;
}
}
public static boolean findValue(List<Integer> input, Integer value) {
int i = 0;
int j = input.size() - 1;
while (i < j) {
if (input.get(i) + input.get(j) == value) {
return true;
} else if (input.get(i) + input.get(j) < value) {
i++;
} else {
j--;
}
}
return false;
}
public static void setUpArray(List<Integer> test) {
for (int i = 0; i < 20; i++) {
int value = (int) (Math.random() * 100);
Value.test.add(value);
}
}
}
This question already has answers here:
Return all prime numbers smaller than M
(9 answers)
Closed 3 years ago.
Can anyone help me to determine all prime numbers smaller than a given input value using scanner with java8 .
Input: N integer> 0
Output: the table with prime numbers.
Example: for N = 10 the Output is : 2 3 5 7
this is my work so far:
class Main {
public static void main(String[] args) {
int N;
int[] result = null;
try (Scanner scanner = new Scanner(new File(args[0]))) {
N = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < (N/2)+1; i++) {
if (N%i==0)
result[i]=i;
for (int j = 0; j < result.length; j++) {
System.out.print(result[j]);
if (j < result.length - 1) {
System.out.print(" ");
}
}
}
System.out.println();
}
catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
}
your code problem is int i = 0 start with 0 and next line if (N%i==0) so 10/0 is not possible throw a error something like java.lang.ArithmeticException: / by zero is not possible
and you loop through result.length, you need to loop through i your parent loop and put condition inside if (N%i==0) and you need many changes saw my below answer and debug where you get unexpected output and follow.
brute Force
public static void main(String[] args) {
int N = 50;
List<Integer> result = new ArrayList<>();
for (int i = 1; i < N; i++) {
boolean isPrime = true;
for (int j = 2; j < i - 1; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result.add(i);
}
}
result.forEach(System.out::println);
}
optimize one using Math.sqrt reason
public static void main(String[] args) {
int N = 101;
List<Integer> result = new ArrayList<>();
for (int i = 1; i <= N; i++) {
boolean isPrime = true;
for (int j = 2; j < Math.sqrt(i - 1); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result.add(i);
}
}
result.forEach(System.out::println);
}
using BigInteger.isProbablePrime see
public static void main(String[] args) {
int N = 101;
List<Integer> result = new ArrayList<>();
for (long i = 1; i <= N; i++) {
BigInteger integer = BigInteger.valueOf(i);
if (integer.isProbablePrime(1)) {
result.add((int) i);
}
}
result.forEach(System.out::println);
}
Updated 1:- that something you want
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
int[] result = new int[N];
int resultIncreamenter = 0;
// here for loop logic can be replaced with above 3 logic
for (int i = 1; i <= N; i++) {
boolean isPrime = true;
for (int j = 2; j < Math.sqrt(i - 1); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result[resultIncreamenter++] = i;
}
}
for (int j = 0; j < result.length; j++) {
System.out.print(result[j]);
if (j < result.length - 1) {
System.out.print(" ");
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
You lost the overview, though you have all functionality within reach.
public static boolean isPrime(int n) {
for (int i = 0; i < (n/2)+1; i++) {
if (n%i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
boolean printed = false;
for (int j = 2; j < N; j++) {
if (isPrime(j)) {
if (printed) {
System.out.print(" ");
}
System.out.print(j);
printed = true;
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
Simply use abstractions like isPrime.
Now for improvements (your results array): use the already found primes instead of all numbers in testing:
public static boolean isPrime(int n, int[] priorPrimes, int primesCount) {
for (int p : priorPrimes) {
if (n%p == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
int[] primes = new int[N];
int primesCount = 0;
boolean printed = false;
for (int j = 2; j < N; j++) {
if (isPrime(j)) {
primes[primesCount] = j;
++primesCount;
if (printed) {
System.out.print(" ");
}
System.out.print(j);
printed = true;
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
The algorithm using the Sieve of Eratosthenes taken from here:
private static int findNumberOfPrimes(int length) {
int numberOfPrimes = 1;
if (length == 2) {
return 1;
}
int[] arr = new int[length];
//creating an array of numbers less than 'length'
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
//starting with first prime number 2, all the numbers divisible by 2(and upcoming) is replaced with -1
for (int i = 2; i < arr.length && arr[i] != -1; i++) {
for (int j = i; j < arr.length; j++) {
if (arr[j] % arr[i] == 0) {
arr[j] = -1;
numberOfPrimes += 1;
}
}
}
return numberOfPrimes;
}
Update :
and this is how you list them :
package primelessthanN;
public class Main {
public static void main(String[] args) {
int j;
int n;
n = 10;
for (j = 2; j <=n; j++) {
if (isPrime(j))
System.out.println(j);
}
}
private static boolean isPrime(int m) {
for (int i = 2; i <= sqrt(m); i++) {
if (m % i == 0)
return false;
}
return true;
}
}
I want to check if the sum of each row in any matrix is equal. How should I rewrite this to avoid NPE?
I can make it work for "normal" matrices like int[][] a = {{1,2,3}, {4,5,6}}, but I want it to work even when testing with null and empty matrices.
public static boolean allRowSumsEqual(int[][] m) {
boolean a = false;
int x = 0;
int total = rowSum(m[0]);
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
x += m[i][j];
}
if (x != total) {
a = false;
break;
} else {
x = 0;
a = true;
}
}
return a;
}
public static int rowSum(int[] v) {
int vSum = 0;
for (int i = 0; i < v.length; i++) {
vSum += v[i];
}
return vSum;
}
As you said, this does work for most matrices. There are a few places I might check for null, see modified code below:
public static boolean allRowSumsEqual(int[][] m){
if(m == null) return true;
if(m.length == 0) return true;
boolean a = false;
int x = 0;
int total = rowSum(m[0]);
for (int i = 1; i < m.length; i++){
// You can use your own function instead of the inner for loop
x = rowSum(m[i]);
if (x != total) {
a = false;
break;
} else {
x = 0;
a = true;
}
}
return a;
}
public static int rowSum(int[] v){
int vSum = 0;
// Assume a null row has sum 0
if(v == null) return 0;
for (int i = 0 ; i < v.length ; i++){
vSum += v[i];
}
return vSum;
}
You need to define a result or an exception if you want to check for "null" parameter. You can return true if null is valid or false otherwise.
if(m == null) return true;
Empty or one lined matrices can return true all the time and does not require any calculation:
if(m.length < 2) return true;
The line test is more simple, I think:
// expect a positiv result
boolean result = true;
// calculate first line
int firstLine = rowSum(m[0]);
// loop remaining lines
for (int i = 1 ; i < m.length ; i++){
// compare first line with current line
if (firstLine != rowSum(m[i]))
{
// not equal -> change result
result = false;
// break loop
break;
}
}
return result;
public class Snippet {
public static boolean allRowSumsEqual(int[][] m) {
if (null == m || 0 == m.length)
return true;
boolean a = false;
int x = 0;
int total = 0;
if (null != m[0])
total = rowSum(m[0]);
for (int i = 1; i < m.length; i++) {
if (null != m[i]) {
for (int j = 0; j < m[i].length; j++) {
x += m[i][j];
}
} else
x = 0;
if (x != total) {
a = false;
break;
} else {
x = 0;
a = true;
}
}
return a;
}
public static int rowSum(int[] v) {
int vSum = 0;
for (int i = 0; i < v.length; i++) {
vSum += v[i];
}
return vSum;
}
public static void main(String[] args) {
int[][] a = { { 1, 2, 3 }, { 3, 2, 1 }, null };
System.out.println(allRowSumsEqual(a));
int[][] b = { null, null, null };
System.out.println(allRowSumsEqual(b));
}
}
What do you think of this solution:
public static boolean allRowSumsEqual(int[][] m) {
if(m == null) { return false; }
int sum = 0;
for(int i = 0; i < m.length; i++) {
int temp = 0;
if(m[i] == null) { continue; }
for(int j = 0; j < m[i].length; j++) {
temp += m[i][j];
}
if(i == 0) { //is the first row
sum = temp;
}
else if(sum != temp) {
return false;
}
}
return true;
}
How do I print the result in the main method? And how do I loop the "isLucky" method to the array? I posted a little bit ago and was told I should post again with less questions.
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
luckyNumber1 = 7;
luckyNumber2 = 13;
luckyNumber3 = 18;
int[] a=new int[10];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
boolean b = isLucky(a);
int result;
if(b){
result = sum(a);
}
else{
result = sumOfEvens(a);
}
}
public static int sum(int [ ] value)
{
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
static int sumOfEvens(int array[])
{
int sum = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
public static boolean isLucky (int[] array)
{
if ( array[i] == 7 || array[i] == 13 || array[i] == 18 )
return true;
else
return false;
}
// write the static methods isLucky, sum, and sumOfEvens
}
Try this,
public static boolean isLucky(int[] array)
{
for (int i = 0; i < array.length; i++)
{
if (array[i] == 7 || array[i] == 13 || array[i] == 18)
{
System.out.println("Going to return true");
return true;
}
}
return false;
}
printing the result by using System.out.println("Result : "+result); in your main method