I have the below snippet of code to use a recursive method to add the sum of odd numbers.
I have already coded the iterative method successfully that adds the sum of all odd numbers between n and m which are entered by the user. I'd like to reach that goal but am started slow to make sure I understand what is happening.
I know that it makes more sense to do it iteratively, however I am experimenting with the two types to see which is more efficient. I am stuck on the below as it is not doing what i want it to and i can't understand why.
import java.util.*;
public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
int x = add(n);
}
public static int add(int x)
{
if (x == 0)
{
return 0;
}
else
{
return (x + add(x-1));
}
}
}
I have changed the above to the below. It compiles however stops after I enter the number.
import java.util.*;
public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
if (n%2 == 0)
{
System.out.println("The number entered is even");
}
else
{
int x = add(n);
}
}
public static int add(int x)
{
if (x <= 0)
{
return 0;
}
else
{
return (x + add(x-2));
}
}
}
import java.util.*;
public class OddR{
public static void main (String Args [])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter an odd number");
int max = s.nextInt();
if((max% 2) == 0) {
System.out.println(max + " is Even number and therefore is invalid");
}
else{
System.out.println("Enter a greater odd number");
int m = s.nextInt();
if (m <max){
System.out.println("Invalid data");
}
else{
if((m % 2) == 0) {
System.out.println(m + " is Even number and therefore is invalid");
}
else{
int data = (addodd(m)- addodd(max))+max;
System.out.print("sum:"+data);
}
}
}
}
public static int addodd(int m)
{
if(m<=0)
{
return 0;
}
if(m%2 != 0)
{
return (m+addodd(m-1));
}
else
{
return addodd(m-1);
}
}
}
This is the answer recursively of the sum of odd numbers from n to m
public int addOdds(int n) {
if (n <= 0) {
return 0;
}
if (n % 2 == 0) {
return addOdds(n - 1);
}
return x + addOdds(n - 1);
}
Take care, I never tested the code.
class Oddsum {
public int addodd(int n)
{
if(n<=0)
{
return 0;
}
if(n%2 != 0)
{
return (n+addodd(n-1));
}
else
{
return addodd(n-1);
}
}
}
public class Xyz {
public static void main (String[] v)
{
int n = 9;
Oddsum o = new Oddsum();
int data = o.addodd(n);
System.out.print("sum:"+data);
}
}
This is working fine
public static void main (String[] args){
public static int oddSum(int s){
if (s <= 0)
return 0;
else
return s + oddSum(s -2);
}
}
Related
I am trying to write a program that creates an array and fill it with int numbers(first method). In the end, it is supposed to see if a specific number is given in the array(second method). The problem is that the program does not run my if loops. I do not know why.
The variable x is the number the program is looking for in the array and pos the position of the number in the array
public class Program {
static int [] numbers= new int[100];
public static void main(String [] args) {
PrintWriter out = new PrintWriter(System.out);
arrayConstruction();
test(out);
out.flush();
}
public static void arrayConstruction() {
int x = 0;
for (int i = 0; i < numbers.length; i++) {
numbers[i] = x;
x++;
}
}
public static void test(PrintWriter out) {
int x = 17;
int pos = 0;
if(pos != numbers.length) {
if(numbers[pos] == x) {
out.println("The number was found!");
out.flush();
}
pos++;
}
else if(pos == numbers.length) {
out.println("The number does not exist!");
out.flush();
}
}
}
You forgot to add a loop to the test method, so it checks the first array's item only. E.g. you can use while loop.
public static void test(PrintWriter out) {
int x = 17;
int pos = 0;
while (true) {
if (pos != numbers.length) {
if (numbers[pos] == x) {
out.println("The number was found!");
return;
}
pos++;
} else if (pos == numbers.length) {
out.println("The number does not exist!");
return;
}
}
}
I think you should redesign your code by splitting different activities with separate methods. It makes your code clear to understand.
public class Main {
public static void main(String[] args) {
int[] arr = createArray(100);
System.out.println(isNumberExist(arr, 17) ? "The number was found!"
: "The number does not exist!");
}
public static int[] createArray(int total) {
int[] arr = new int[total];
Random random = new Random();
for (int i = 0; i < arr.length; i++)
arr[i] = random.nextInt(arr.length);
return arr;
}
public static boolean isNumberExist(int[] arr, int x) {
for (int i = 0; i < arr.length; i++)
if (arr[i] == x)
return true;
return false;
}
}
You should add a while loop to your test method, like this:
public static void test(PrintWriter out) {
int x = 17;
int pos = 0;
while(pos < numbers.length) {
if(numbers[pos] == x) {
out.println("The number was found!");
out.flush();
break;
}
pos++;
}
if(pos == numbers.length) {
out.println("The number does not exist!");
out.flush();
}
}
In your method, the if statement will only be executed once.
I'm very new to binary search and I attempted a code that would read values from a document and then the user can input a number to search for from the document, and through binary search, the number would be found. I'm having trouble now because the "low" variable that I initialize in the binary search section of my code is not being returned to my main code and there's an error that says "low can not be resolved to a variable".
Here is the code for my binary search:
static public int search (int[]numbers,int target, int count)
{
int high = numbers.length;
int low = -1;
int middle = (high+low)/2;
while(high-low>1)
{
count++;
middle = (high+low)/2;
if(numbers[middle]>target)
{
high = middle;
}
else if(numbers[middle]<target)
{
low = middle;
}
else
{
break;
}
System.out.println(numbers[middle]);
System.out.println(middle);
}
if(low == -1 || numbers[low]!=target)
{
low=-1;
return low;
}
else
{
return low;
}
}
And here is the code from my main code. The part with the if statements is where the error is showing up:
public static void main(String[] args) throws IOException {
DataInputStream input = new DataInputStream(System.in);
int [] numbers = new int [50000];
int target;
int count=0;
try
{
BufferedReader br = new BufferedReader(new FileReader("randNums.txt"));
for(int i=0;i<50000;i++)
{
numbers[i]=Integer.parseInt(br.readLine());
}
br.close();
Arrays.sort(numbers);
System.out.print("Choose a number between 1-100000000 to search for: ");
target = Integer.parseInt(input.readLine());
search(numbers, target,count);
if(low==-1)
{
System.out.println("The number was not on the list.");
}
else
{
System.out.println("The number is at position " + low);
System.out.println("It took " + count + " comparisons to find the number.");
}
}
You have to initialize low in main:
int low=search(numbers, target,count);
I have Already resolved this algorithm.
Try my code :
public static int guessNumber(int number) {
int first = 0;
int last = 1_000_000;
if (verify(first) == 0) {
count++;
return first;
}
if (verify(last) == 0) {
count++;
return last;
}
while (last > first && count <= 50) {
count += 1;
// get the middle of the range
int middle = (first + last) / 2;
if (verify(middle) == 0) {
return middle;
}
if (verify(middle) == 1) {
first = middle + 1;
if (verify(first) == 0) {
return first;
}
}else {
last = middle - 1;
if (verify(last) == 0)
return last;
}
}
return 0;
}
//Function verify(integer) => integer
public static int verify(int guess){
if (numberTobeGuessed > guess ) {
return 1;
}else if (numberTobeGuessed < guess) {
return -1;
}
return 0;
}
I recently found a solution for lazy peoples like me use below code
int position = Arrays.binarySearch(numbers , target);
here no need to sort, and array variable number integer variable target.
I have the following simple recursive Fibonacci code:
public class FibPrac5202016
{
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter index number: ");
int integer = input.nextInt();
FibPrac5202016 object = new FibPrac5202016();
System.out.println(object.operation(integer));
}
public static long operation(long n) {
if(n==0)
return 0;
if(n==1)
return 1;
try {
if( n < 0)
throw new Exception("Positive Number Required");
}
catch(Exception exc)
{
System.out.println("Error: " + exc.getMessage());
}
return operation((n-1))+operation((n-2));
}
}
As I recently learned about exceptions, I'm trying to use that here when the user inputs negative integer.However, my program runs into StackOverflowError.
Well yes, because you recurse after you catch an Exception. You could trivially fix it by returning -1 in the catch.
catch(Exception exc)
{
System.out.println("Error: " + exc.getMessage());
return -1;
}
or not throwing an Exception in the first place like
public static long operation(long n) {
if (n < 0) {
return -1;
} else if (n == 0) {
return 0;
} else if (n == 1 || n == 2) {
return 1;
}
return operation((n-1))+operation((n-2));
}
or you could implement the Negafibonaccis. And, you could extend it to support BigInteger (and optimize with memoization) like
private static Map<Long, BigInteger> memo = new HashMap<>();
static {
memo.put(0L, BigInteger.ZERO);
memo.put(1L, BigInteger.ONE);
memo.put(2L, BigInteger.ONE);
}
public static BigInteger operation(long n) {
if (memo.containsKey(n)) {
return memo.get(n);
}
final long m = Math.abs(n);
BigInteger ret = n < 0 //
? BigInteger.valueOf(m % 2 == 0 ? -1 : 1).multiply(operation(m))
: operation((n - 2)).add(operation((n - 1)));
memo.put(n, ret);
return ret;
}
the problem is that these throws a execcion within a try block and this creates a cycle in which is testing the code and as always will be a smaller number than 0 always threw the exception infinitely until the exception is given
Exception in thread "main" java.lang.StackOverflowError
I think the solution is to make the program a stop when you find a number less than 0
as follows
public class FibPrac5202016 {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter index number: ");
int integer = input.nextInt();
FibPrac5202016 object = new FibPrac5202016();
System.out.println(object.operation(integer));
}
public static long operation(long n) {
if(n==0)
return 0;
if(n==1)
return 1;
try
{
if( n < 0)
throw new Exception("Positive Number Required");
}
catch(Exception exc)
{
System.out.println("Error: " + exc.getMessage());
//return -1;
}
return operation((n-1))+operation((n-2));
}
}
I have a multiphase homework due soon and my I'm on my last leg of it, but I'm very confused by it. The first assignment has me instantiating different Primes that all are dependent on each other and are all effected together no matter which one I refer to. The second part that I'm having trouble with is making it instantiable so that each Prime is effect independently and doing so by making a second class to show that they are independent.
My first class is this:
package project1;
public class Prime {
//Part 2: Primes
//Place your methods in here
public static void main (String[] args) {
Prime p = new Prime();
Prime p2 = new Prime();
p.getPrime();
p2.getPrime();
Prime.getPrime();
p.reset();
p2.getPrime();
p2.sumPrimes(4);
p2.getPrime();
p.getPrime();
}
static int num = 0;
static int count = 0;
public static boolean isPrime(int p) {
if (p <= 1){
return false;
}
for (int i = 2; i < p; i++) {
if (p % i == 0) {
return false;
}
}
return true;
}
public static int getPrime() {
while (Prime.isPrime(num) == false) {
num ++;
}
if (Prime.isPrime(num) == true) {
System.out.println(num);
num ++;
return num;
}
return num;
}
public static void reset() {
num = 0;
}
public static int reset(int n) {
num = n;
while (Prime.isPrime(num) == false) {
num ++;
}
if (Prime.isPrime(num) == true) {
return num;
}
return num;
}
public static int sumPrimes(int n) {
int sum = 0;
while (n > count) {
while (Prime.isPrime(num) == false) {
num ++;
}
if (Prime.isPrime(num) == true) {
sum += num;
count ++;
num ++;
}
}
System.out.println(sum);
return num;
}
}
I know it's not the prettiest code, but I'm a Java beginner. I only need to take this and make it so p and p2 are two separate variables by using instantiation and a new class called PrimeTest that has a main method that shows their independent. Anyone have any tips or examples I can look at?
I was trying to build a Java program for finding the LCM of 'N' numbers. but first of all i am stuck at finding the total prime factors of a number including their occurrences. For example (6=2x3) and (8=2x2x2). but the output i get is '2' for (6) and only two '2's for (8). Where are the other? I am even checking the integer 's' to be prime.
package lcm;
import java.util.ArrayList;
import java.util.Scanner;
public class LCM {
public static boolean isPrime(int numero){
for (int i = 2; i <= Math.sqrt(numero); i++) {
if (numero % i == 0) {
return false;
}
}
return true;
}
public static void factor(int x){
int s;
int copy = x;
ArrayList<Integer> al = new ArrayList<>();
for(s=2;s<copy;s++){
if(copy%s==0){
if (isPrime(s)){
al.add(s);
copy/=s;
//used for repetition
s--;
}
}
}
for( int p : al){
System.out.println(p);
}
}
public static void main(String[] args) {
// TODO code application logic here
int j,k;
int temp=0;
System.out.println("Enter no. of numbers");
Scanner cin = new Scanner(System.in);
int i = cin.nextInt();
int []a = new int[i];
int []b=new int[100];
System.out.println("Enter numbers one by one");
for(j=0;j<a.length;j++){
a[j] = cin.nextInt();
}
for(j=0;j<a.length;j++){
temp=a[j];
factor(temp);
}
}
}
The reason is when s=2 and copy also becomes 2 in a case at that time it skips the loop so only two 2's are shown. Try putting <=copy in that place
I think one of the best way to approach this problem is to use recursion since you continuously have to divide in order to find all the prime factors.
package leastcommonmultiple;
import java.util.ArrayList;
import java.util.Scanner;
public class Runner {
private static LeastCommonMultiple lcm;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Enter numbers and separate them with a comma: ");
Scanner cin = new Scanner(System.in);
String[] inputs;
String lineInput;
try {
lineInput = cin.nextLine();
while (lineInput.isEmpty()) {
System.out.println("Enter at least 2 numbers separated by a comma ");
lineInput = cin.nextLine();
}
inputs = lineInput.split(",");
int length = inputs.length;
int[] numbers = new int[length];
int temp = 0;
for (int i = 0; i < length; i++) {
if (inputs[i] != null && !inputs[i].isEmpty()) {
if ((temp = Math.abs(Integer.valueOf(inputs[i].trim()))) == 0) {
throw new IllegalArgumentException("No number should be 0");
}
numbers[i] = temp;
}
}
ArrayList<Integer> list = new ArrayList<>();
lcm = new LeastCommonMultiple();
System.out.println("The Least Common Multiple is: " + lcm.getLeastCommonMultipleOfListOfNumbers(numbers));
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
package leastcommonmultiple;
import java.util.ArrayList;
public class LeastCommonMultiple {
public LeastCommonMultiple() {
}
/**
* #param numbers array of numbers whose LCM should be found.
* #assure numbers.length > 1
* #return LCM of numbers contained in numbers array
*/
public int getLeastCommonMultipleOfListOfNumbers(int[] numbers) throws IllegalArgumentException {
int leastCommonMultiple;
int length = numbers.length;
if ( length <= 1) {
throw new IllegalArgumentException("Please enter at least 2 numbers separated by a comma.");
} else {
leastCommonMultiple = getLeastCommonMultipleOfTwoNumbers(numbers[0], numbers[length-1]);
length = length-1;
for ( int i=1; i<length; i++ ) {
leastCommonMultiple = getLeastCommonMultipleOfTwoNumbers(leastCommonMultiple, numbers[i]);
}
}
return leastCommonMultiple;
}
private int getLeastCommonMultipleOfTwoNumbers(int number1, int number2) {
int leastCommonMultiple = 0;
int maxOfTheTwoNumbers = Math.max(number1, number2);
int minOfTheTwoNumbers = Math.min(number1, number2);
int quotient = 0;
if (number1 % number2 == 0 || number2 % number1 == 0) {
leastCommonMultiple = maxOfTheTwoNumbers;
} else {
ArrayList<Integer> primeFactors = getPrimeFactors(minOfTheTwoNumbers, new ArrayList<>());
for (int primeFactor : primeFactors) {
if (maxOfTheTwoNumbers % primeFactor == 0) {
maxOfTheTwoNumbers = (maxOfTheTwoNumbers / primeFactor);
}
leastCommonMultiple = minOfTheTwoNumbers * maxOfTheTwoNumbers;
}
}
return leastCommonMultiple;
}
// recursive methods that finds all the prime factors for a given number
/**
* #param numero positive number whose prime factors has to be found
* #param primeFactors an empty ArrayList where the prime factors will be
* stored
* #return the ArrayList containing the found prime factors
*/
private static ArrayList<Integer> getPrimeFactors(int numero, ArrayList<Integer> primeFactors) {
int sqrt = (int) Math.sqrt(numero);
int quotient;
if (isPrime(numero)) {
primeFactors.add(numero);
} else {
if (numero % sqrt == 0) {
quotient = numero / sqrt;
if (isPrime(sqrt)) {
primeFactors.add(sqrt);
} else {
primeFactors = getPrimeFactors(sqrt, primeFactors);
}
} else {
quotient = numero / (sqrt - 1);
if (isPrime(sqrt - 1)) {
primeFactors.add(sqrt - 1);
} else {
primeFactors = getPrimeFactors((sqrt - 1), primeFactors);
}
}
if (!isPrime(quotient)) {
primeFactors = getPrimeFactors(quotient, primeFactors);
} else {
primeFactors.add(quotient);
}
}
return primeFactors;
}
// Make sure a number is prime
public static boolean isPrime(int numero) {
int length = (int) Math.sqrt(numero);
for (int i = 2; i <= length; i++) {
if (numero % i == 0) {
return false;
}
}
return true;
}
}
Here's a solution which is faster by using binary splitting on the Euclidean algorithm:
private static int gcd(int a, int b) {
if (a == 0) return b;
if (b == 0) return a;
return gcd(b, a%b);
}
private static int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
public static int LCM(int[] numbers) {
int len = numbers.length;
if (len == 2) return lcm(numbers[0], numbers[1]);
if (len == 1) return numbers[0];
if (len == 0) return 1;
int[] left = Arrays.copyOfRange(numbers, 0, len/2);
int[] right = Arrays.copyOfRange(numbers, len/2+1, len);
return lcm(LCM(left), LCM(right));
}