The code is supposed to write a Java program that reads from the standard input a list of positive integers and determines if any of them can be written as the sum of a subset of the other input integers. Hints: Searching for subsets of integers that add up to a certain value is best done recursively. However, avoid generating all subsets. When you search for a subset with sum x, input integers larger than x do not have to be considered. If y≤x is one of the other input integers, the search for subsets summing up to x can be divided into searching among subsets that include y and those that don't.
import java.util.Scanner;
import java.util.Arrays;
public class jodiejo {
public static int[] integers = new int[1000];
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = 0;
integers = new int[1000];
while (scan.hasNextInt()) {
integers[n] = scan.nextInt();
n++;
}
for (int i = 0; i < n; i++) {
searchSum(integers[i], i);
}
System.out.print("NO");
Arrays.sort(integers, 0, n);
}
public static void searchSum(int number, int position) {
for (int i = position - 1; i >= 0; i--) {
if (number - integers[i] == 0) {
System.out.print("YES");
System.exit(0);
} else if (number - integers[i] > 0) {
searchSum(number - integers[i], i);
} else if (number - integers[i] < 0) {
return
}
}
}
}
You need a semicolon after that last return, i.e:
public static void searchSum(int number, int position) {
for (int i = position - 1; i >= 0; i--) {
if (number - integers[i] == 0) {
System.out.print("YES");
System.exit(0);
} else if (number - integers[i] > 0) {
searchSum(number - integers[i], i);
} else if (number - integers[i] < 0) {
return;
}
}
}
Your problem is here, you don't have semicolon after return statement:
else if(number - integers[i] < 0)
{
return //No Semicolon
}
in line:49
instead of return , return; - missing ;
I think the error must be here:
else if(number - integers[i] < 0)
{
return //this is the problem
}
}
So just put a semi colon ; after return like return;
And why are you initializing your integers array second time inside the main method:
integers = new int[1000];
It is redundant.
import java.util.Scanner;
import java.util.Arrays;
public class jodiejo
{
public static int[] integers = new int[1000];
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int n = 0;
integers = new int[1000];
while (scan.hasNextInt())
{
integers[n] = scan.nextInt();
n++;
}
for (int i = 0; i < n; i++)
{
searchSum(integers[i], i);
}
System.out.print("NO");
Arrays.sort(integers, 0, n);
}
public static void searchSum(int number,
int position)
{
for (int i = position - 1; i >= 0; i--)
{
if (number - integers[i] == 0)
{
System.out.print("YES");
System.exit(0);
}
else if (number - integers[i] > 0)
{
searchSum(number - integers[i], i);
}
else if (number - integers[i] < 0)
{
return;
}
}
}
}
Related
My code doesn't work and i don't know either why or how to make it work. This is my code.
public static void ex5(){
Scanner scan = new Scanner(System.in);
int givenNr = scan.nextInt();
int m = 1;
for (int i = 2; i < givenNr; i++){
while (m <= i/2 ){
if(i % m != 0) {
System.out.print(i + " ");
}
m++;
}
}
}
public static void ex5() {
Scanner scan = new Scanner(System.in);
int givenNr = scan.nextInt();
for (int i = 2; i < givenNr; i++) {
if (isPrime(i))
System.out.println(i);
}
}
public static boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}
I have to print prime factor of any number in this format. Ex: 32 = 2*2*2*2*2
Heres my code. It works fine for all except for 32, it gives:2*2*2*2*2*
How to avoid the last *.
Heres my code:
public class PF{
public static void pf(int n) {
for(int i = 2; i< n; i++) {
while(n%i == 0) {
System.out.print(i+ "*");
n = n/i;
}
}
if (n > 2) System.out.print(n);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
pf(n);
}
Other option, you can avoid the * when n=i in your while loop
public static void pf(int n) {
for (int i = 2; i < n; i++) {
while (n % i == 0) {
System.out.print(i);
if (n != i) {
System.out.print("*");
}
n = n / i;
}
}
if (n > 2)
System.out.print(n);
}
One option is to store the values in a list and print them together like this:
public static void pf(int n) {
List<String> l = new ArrayList<>();
for (int i = 2; i < n; i++) {
while (n % i == 0) {
l.add(String.valueOf(i));
n = n / i;
}
}
System.out.print(String.join("*", l));
if (n > 2) {
System.out.print("*" + n);
}
}
I did this in two ways.
Type 1
public static void pf(int n) {
for(int i = 2; i< n; i++) {
while(n%i == 0) {
System.out.print(i+ "*");
n = n/i;
System.out.print(i>n ? "\b" : ""); //Backspase and remove unwanted character(*) after print
}
}
if (n > 2) System.out.print(n);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
pf(n);
}
Type 2
public static void pf(int n) {
for(int i = 2; i< n; i++) {
while(n%i == 0) {
System.out.print(i+ ((i<n) ? "*" : "")); //Skip the unwanted character(*)
n = n/i;
}
}
if (n > 2) System.out.print(n);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
pf(n);
}
You have a formatting problem. It makes sense to separate it from the initial calculation; better to deal with different problems separately.
You can generate a list of prime factors and write a method to print the list in the correct format. For this general problem I tend to treat the list as a head with one item that is not preceded by the separator and a tail with all the other entries, each of which is preceded by the separator, your '*' or perhaps a comma in the more common case. Rather than suppressing the separator after the last entry in the list, think of it as suppressing the separator before the first entry. It is easier to identify the first element in a list than the last.
My code is not strict Java, but gives you the general idea.
void printSeparatedList(factorList) {
char separator = '*';
bool firstEntry = true;
for (int factor : factorList) {
if (firstEntry) {
firstEntry = false;
} else {
System.out.print(separator);
}
System.out.print(factor);
}
} // End printSeparatedList
in java what i am trying to do is have a user input a value greater than 0 and with that number they input list that amount of prime numbers starting from 2
so if the user inputs "3" the program will display 2,3,5
if the user inputs "5" the program will display 2,3,5,7,11
and so on
the problem is I cant figure out how to have the user input do this correctly, i either end up with the numbers repeating however many times or the list ending at the user input, any help would be apreciated
import java.util.Scanner;
public class Primes
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int n = console.nextInt();
if(n<=0)
{
return;
}
else
{
for(int i=2; i < 100; i++)
{
boolean isPrime = true;
for(int j=2; j < i; j++)
{
if(i%j == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
System.out.println(i);
}
}
}
}
}
Keep a count of how many primes have been found by changing your for loop to stop when you've found enough primes and performing primesFound++ when a prime is found:
for (int i = 2, primesFound = 0; primesFound < n; i++)
{
boolean isPrime = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
System.out.println(i);
primesFound++;
}
}
I rather have code that is refactored, each method is doing one thing, it makes it much easier to read, debug and maintain.
All we need to do is separate the logic that checks if a number is prime from the logic that goes over the numbers until n prime numbers are found:
public static void main(String[] args) {
printNPrimes(5);
}
static private boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
static private void printNPrimes(int n) {
int i = 2;
while (n > 0) {
if (isPrime(i)) {
System.out.println(i + " is Prime");
n--;
}
i++;
}
}
//prime
int i,j;
Set<Integer> primeNums = new HashSet<>();
Set<Integer> notPrimeNums = new HashSet<>();
Stack<Integer> stack = new Stack<>();
for(i=1; i<fiboList.size(); i++) {
for(j=i+1; j<fiboList.size(); j++) {
if( i % j == 0 ) {
notPrimeNums.add(fiboList.get(i));
}else {
primeNums.add(fiboList.get(i));
}
}
}
stack.addAll(primeNums);
Collections.sort(stack);
System.out.println("Prime numbers:"+" "+stack);
}
I have code that can make output prime number but this program using try and catch. Can you help me change this program with using recursive?
package file;
import javax.swing.JOptionPane;
public class Snake {
private static int getNilai(int number, int index) {
if (index == 1)
return 1;
else if (number % index == 0)
return 1 + getNilai(number, --index);
else
return 0 + getNilai(number, --index);
}
public static boolean cekPrime(int num) {
if (num > 1)
return (getNilai(num, num) == 2);
else
return false;
}
public static void main(String[] args) {
while (true) {
try {
int n = Integer.parseInt(JOptionPane
.showInputDialog("Enter your number!"));
if (n > 0) {
int a = 0;
int b = 0;
int p[] = new int[n * n];
while (b < (n * n)) {
if (cekPrime(a)) {
p[b] = a;
b++;
}
a++;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int m = ((i + 1) + (j * n)) - 1;
System.out.print(p[m] + "\t");
}
System.out.println();
}
break;
} else {
JOptionPane.showMessageDialog(null,
"Sorry, your input must be higher than 0!",
"System Error", JOptionPane.ERROR_MESSAGE);
}
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,
"You must entering number not word!", "System Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
The code uses try-catch because of this line
int n = Integer.parseInt(JOptionPane.showInputDialog("Enter your number!"));
not because of "non-recursiveness". To make a program recursive, put the logic into a method an instead of performing a loop, invoke the method itself again. The invocation is only performed if a condition is (not) true. In this case, do not invoke the method again but return the calculated value (or something else)
Besides this there is much easier code to check a number to be prime...
So I can easily accomplish task to find largest number and then if can be divided by three, print out. But do not know how to find second largest number from users sequence.
Thanks for any hints!
public class SecondLargest {
public static void main(String[] args) {
int max = 0;
Scanner scan = new Scanner(System.in);
System.out.println("How many numbers?");
int n = scan.nextInt();
System.out.println ("Write numbers: ");
for(int i=0; i<n; i++){
int c = scan.nextInt();
if(c>=max && c%3 == 0){
max = c;
}
else
System.out.println("There is no such number.");
}
System.out.println(max);
}
}
int secondLargest = 0;
.....
for (..) {
....
if (c % 3 == 0) {
if (c >= max) {
secondLargest = max;
max = c;
}
if (c >= secondLargest && c < max) {
secondLargest = c;
}
}
....
}
You just need to keep 2 variables, one for maximum and another for second_maximum and update them appropriately.
For a more general approach, take a look at selection algorithms
Below code will work
import java.util.Scanner;
public class Practical4 {
public static void main(String a[]) {
int max = 0, second_max = 0, temp, numbers;
Scanner scanner = new Scanner(System.in);
System.out.println("How many numbers do you want to enter?");
numbers = scanner.nextInt();
System.out.println("Enter numbers:");
for (int i = 0; i < numbers; i++) {
if (i == 0) {
max = scanner.nextInt();
} else {
temp = scanner.nextInt();
if (temp > max) {
second_max = max;
max = temp;
}
else if(temp>second_max)
{
second_max=temp;
}
}
}
scanner.close();
System.out.println("Second max number is :" + second_max);
}
}