Cannot find symbol - variable java - java

I am trying to do the following program in Java where I'm writing a recursive and an iterative method to compute the sum of all odd numbers from n to m
import java.util.Scanner;
public class AssignmentQ7 {
public static int recursivesum(int n, int m){
if (n < m){
int s = n;
s += recursivesum(n+2, m);
} else{
if(m < n){
int s = m;
s += recursivesum(m+2, n);
}
}
return s;
}
public static int iterativesum(int n, int m){
if(n < m){
int s = n;
for(int i = n; i <= m; i += 2){
s += i;
return s;
}
} else
if(m < n){
int s = m;
for(int i = m; i <= n; i += 2){
s += i;
return s;
}
}
}
public static void main(String args[]){
int n,m;
Scanner in = new Scanner(System.in);
System.out.println("Enter two numbers: ");
n = in.nextInt();
m = in.nextInt();
while(n%2 == 0){
System.out.println("Enter the first number again: ");
n = in.nextInt();
}
while(m%2 == 0){
System.out.println("Enter the second number again: ");
m = in.nextInt();
}
System.out.println("The answer of the recursive sum is: " + recursivesum(n,m));
System.out.println("The answer of the iterative sum is: " + iterativesum(n,m));
}
}
I'm getting an error cannot find symbol - variable enter code heres. I don't know what's wrong! Can anyone help please?

This method is the problem:
public static int recursivesum(int n, int m) {
if (n < m) {
int s = n; // Variable declared here... scoped to the if
s += recursivesum(n+2, m);
} else {
if (m < n) {
int s = m; // Variable declared here... scoped to this if
s += recursivesum(m+2, n);
}
}
return s; // No such variable in scope!
}
You could use:
public static int recursivesum(int n, int m) {
int s = 0; // See note below
if (n < m) {
s = n + recursivesum(n+2, m);
} else {
if (m < n) {
s = m + recursivesum(m+2, n);
}
}
return s;
}
We have to give s an explicit initial value, because you currently don't have any code handling the case where n and m are equal. It's not clear what you want to do then.
Another alternative is to return from the if statements, just as you do in iterativesum... although you'll again need to think about what to do if m == n:
public static int recursivesum(int n, int m) {
if (n < m) {
// You don't even need an s variable!
return n + recursivesum(n+2, m);
} else if (m < n) {
// Simplified else { if { ... } } to else if { .... }
return m + recursivesum(m+2, n);
} else {
// What do you want to return here?
}
}
Note that you've got the same problem in iterativesum - the compiler should be complaining at you at the moment that not all paths return a value. What do you expect iterativesum(3, 3) to do?

in recursivesum(int n, int m) method, you have declared s within if condition, but, you tried to access it in else part.
public static int recursivesum(int n, int m){
int s = n; // Now s having method local scope
if (n < m){
s += recursivesum(n+2, m);
} else{
if(m < n){
int s = m;
s += recursivesum(m+2, n);
}
}
return s;
}

In the recursivesum(int n,int m) function the scope of variable s is inside the if and else block. When your returning s it is out of scope.
Try using some IDE's like eclipse. So that you can debug these errors instantly

Try this:
int s;
if (n < m){
s = n;
s += recursivesum(n+2, m);
} else{
if(m < n){
int s = m;
s += recursivesum(m+2, n);
}
}
return s;

You are declaring variable s inside if statement, that is why you get such error. Start from declaration int s outside if statement.

your s is out of scope in recursivesum(int n, int m) method

Declare s outside the if-else block

It's scope problem. You're declaring variable s inside the if statements which is (local definition) of variable.
You need to modify the two methods as follows:
The recursive method will be
public static int recursivesum(int n, int m) {
int s = 0;
if (n < m) {
s = n;
s += recursivesum(n + 2, m);
} else {
if(m < n){
s = m;
s += recursivesum(m + 2, n);
}
}
return s;
}
And the iterative method will be:
public static int iterativesum(int n, int m) {
int s = 0;
if(n < m) {
s = n;
for(int i = n; i <= m; i += 2) {
s += i;
}
} else {
if(m < n) {
s = m;
for(int i = m; i <= n; i += 2) {
s += i;
}
}
}
return s;
}

You have an error in the first method where you define s outside the scope which you return it from. In the second method you return inside the loop.
As others in this thread suggests, use an IDE like Eclipse (https://www.eclipse.org/) or IntelliJ (http://www.jetbrains.com/idea/)
import java.util.Scanner;
public class AssignmentQ7 {
public static int recursivesum(int n, int m) {
int s = n;
if (n < m) {
s += recursivesum(n + 2, m);
}
else {
if (m < n) {
s = m;
s += recursivesum(m + 2, n);
}
}
return s;
}
public static int iterativesum(int n, int m) {
int s = 0;
if (n < m) {
for (int i = n; i <= m; i += 2) {
s += i;
}
}
else if (m < n) {
for (int i = m; i <= n; i += 2) {
s += i;
}
}
return s;
}
public static void main(String args[]) {
int n, m;
Scanner in = new Scanner(System.in);
System.out.println("Enter two numbers: ");
n = in.nextInt();
m = in.nextInt();
while (n % 2 == 0) {
System.out.println("Enter the first number again: ");
n = in.nextInt();
}
while (m % 2 == 0) {
System.out.println("Enter the second number again: ");
m = in.nextInt();
}
System.out.println("The answer of the recursive sum is: " + recursivesum(n, m));
System.out.println("The answer of the iterative sum is: " + iterativesum(n, m));
}
}

Your code must be like this, you dont have to use two for loop.
import java.util.Scanner;
public class AssignmentQ7 {
public static int recursivesum(final int n, final int m) {
final int lower = n < m ? n : m;
final int upper = n > m ? n : m;
final int total = lower;
if (lower >= upper) {
return total;
}
return total + AssignmentQ7.recursivesum(lower + 2, upper);
}
public static int iterativesum(final int n, final int m) {
final int lower = n < m ? n : m;
final int upper = n > m ? n : m;
int total = 0;
for (int num = lower; num <= upper; num = num + 2) {
total += num;
}
return total;
}
public static void main(final String args[]) {
int n, m;
final Scanner in = new Scanner(System.in);
System.out.println("Enter two numbers: ");
n = in.nextInt();
m = in.nextInt();
while (n % 2 == 0) {
System.out.println("Enter the first number again: ");
n = in.nextInt();
}
while (m % 2 == 0) {
System.out.println("Enter the second number again: ");
m = in.nextInt();
}
System.out.println("The answer of the recursive sum is: " + AssignmentQ7.recursivesum(n, m));
System.out.println("The answer of the iterative sum is: " + AssignmentQ7.iterativesum(n, m));
}
}

Related

fibonacci and prime numbers in one series

I am trying to do some mock questions of coding for an entrance exam, I came about this question and I am stuck at the PRIME NUMBERS part.
Here is the question:
Consider the below series: 1, 2, 1, 3, 2, 5, 3, 7, 5, 11, 8, 13, 13, 17, … This series is a mixture of 2 series – all the odd terms in this series form a Fibonacci series and all the even terms are the prime numbers in ascending order. Write a program to find the Nth term in this series. For example, when N = 14, the 14th term in the series is 17. So only the value 17 should be printed out.
public class OandF {
// main
public static void main(String[] args) {
System.out.println(dofibo(9));
}
public static int dofibo(int m) {
if(m == 0) {
return 0;
}
if(m == 1) {
return 1;
}
return dofibo(m-1) + dofibo(m-2);
}
}
// as you can see this is where I got to, and I don't know how to proceed
There are multiple ways to find the nth Prime number, the easiest way is to keep counting the prime numbers from 1 to n. But this is very time consuming otherwise refer to Fermat's theorems or Sieve of Eratosthenes.
private boolean isPrime(int n) {
if (n == 2 || n == 3) return true;
for(int i = 2; i < (int)Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public int nthPrime(int n) {
int number, primeCount;
for(number = 2, primeCount = 0; primeCount < n; number++) {
if (isPrime(number)) {
++primeCount;
}
}
return number;
}
You can try this, it may solve your problem.
class FibonacciExample1 {
public static void main(String args[]) {
int input = 20;
fibonacci(input);
System.out.print("-----------------------------");
prime(input);
}
public static void fibonacci(int input) {
int n1 = 0, n2 = 1, n3, i, count = input;
System.out.print(n1 + " " + n2);
for (i = 2; i < count; ++i) {
n3 = n1 + n2;
System.out.print(" " + n3);
n1 = n2;
n2 = n3;
}
}
public static void prime(int input) {
int i = 0;
int num = 0;
String primeNumbers = "";
for (i = 1; i <= input; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println(primeNumbers);
}
}
I'd make these two programs into simpler, infinite generators that are easier to debug and then sequence:
import java.util.ArrayList;
class Fibonacci {
int a = 0, b = 1;
int next() {
int c = a;
a = b;
b += c;
return a;
}
}
class Prime {
ArrayList<Integer> primes = new ArrayList<>();
int number = 2;
int next() {
if (number == 2) { // special case
primes.add(number);
number = 1;
return 2;
}
outer: while (true) {
number += 2;
for (int divisor: primes) {
if (divisor * divisor > number) {
break outer;
}
if (number % divisor == 0) {
break;
}
}
}
primes.add(number);
return number;
}
}
public class Example {
public static int sequence(int n) {
int nth = -1;
if ((n % 2) == 0) {
Fibonacci fibonacci_generator = new Fibonacci();
for (int i = 0; i < (n / 2) + 1; i++) {
nth = fibonacci_generator.next();
}
} else {
Prime prime_generator = new Prime();
for (int i = 0; i < (n + 1) / 2; i++) {
nth = prime_generator.next();
}
}
return nth;
}
public static void main(String args[]) {
System.out.println(sequence(13)); // 14th element counting from zero
}
}

Why doesn't my program run correctly?

for my school project I have to create a program that outputs perfect numbers based on how many perfect numbers the user(teacher) want. The user can pick any number from 1-4 and it should display however many number the user chooses. Here is my current code. Please ignore the sumupTo, factorial, isprime, and the testGoldbach methods, please only look at the Perfect numbers method/code.
import java.util.Scanner;
public class MyMathB
{
public static int sumUpTo(int n)
{
int sum = 0;
for (int k = 1; k <= n; k++)
sum += k;
return sum;
}
public static long factorial(int n)
{
long f = 1;
for (int k = 2; k <= n; k++)
f *= k;
return f;
}
public static boolean isPrime(int n)
{
if (n <= 1)
return false;
int m = 2;
while (m * m <= n)
{
if (n % m == 0)
return false;
m++;
}
return true;
}
public static void PerfectNumbers(int number)
{
System.out.println("How many perfect numbers would you like to see? Please enter an integer from 1 to 4");
Scanner s = new Scanner(System.in);
int numbersToSee = s.nextInt();
int counts = 0;
for(counts = 0; counts <= numbersToSee; counts++)
{
for (int n = 5; n <= 10000; n++)
{
int temp = 0;
for(int i = 1; i <= number / 2; i++)
{
if (number % i == 0)
{
temp += i;
}
if (temp == number)
{
System.out.println(number);
}
}
}
}
}
public static boolean testGoldbach(int bigNum)
{
for (int n = 6; n <= bigNum; n += 2)
{
boolean found2primes = false;
for (int p = 3; p <= n/2; p += 2)
{
if (isPrime(p) && isPrime(n - p))
found2primes = true;
}
if (!found2primes)
{
System.out.println(n + " is not a sum of two primes!");
return false;
}
}
return true;
}
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int n;
do
{
System.out.print("Enter an integer from 4 to 20: ");
n = kb.nextInt();
} while (n < 4 || n > 20);
kb.close();
System.out.println();
System.out.println("1 + ... + " + n + " = " + sumUpTo(n));
System.out.println(n + "! = " + factorial(n));
System.out.println("Primes: ");
for (int k = 1; k <= n; k++)
if (isPrime(k))
System.out.print(k + " ");
System.out.println();
System.out.println("Goldbach conjecture up to " + n + ": " + testGoldbach(n));
}
}
you didn't declare the variable "number" in your method.
Edit: you didn't SET the variable number to anything, I misworded my last statement.

How to write a function that implements Euclid's Algorithm for computing the greatest common divisor ( m,n)?

I'm trying to add the gcd() function to the NumericFunctions class and include code in main to compute gcd(m,n).
However, I keep getting an error:
Exception in thread "main" java.lang.StackOverflowError
at NumericFunctions.gcd(NumericFunctions.java:14)
Source code:
public class NumericFunctions {
public static long factorial(int n) {
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static int gcd (int n, int m) {
if ((m % n) == 0)
return n;
else
return gcd(n, m % n);
}
public static void main(String[] args) {
for (int n = 1; n <= 10; n++)
for (int m = 1; m <= 10; m++){
System.out.println(gcd(n,m));
System.out.println(" ");
System.out.println(factorial(n));
}
}
}
Check out the following corrections in gcd() method:
public static int gcd (int n, int m) {
if ((n % m) == 0)
return m; // <-- first correction
else
return gcd(m, n % m); // <-- second correction
}

How to find the GCD of three numbers within a single method

I've got to ensure that the GCD between 3 numbers is no greater than 1.
Here's the code I have so far for the method:
private int greatestCommonFactor(int a, int b, int c)
{
for(int n = 0; n <= number; n++)
{
if()
}
return 1;
}
the return 1 was already there when I started working on the lab. How can I make sure that the GCD is no more than 1? And return all three integers?
Here's the remainder of the code if it helps in figuring out what needs to be done:
import static java.lang.System.*;
public class Triples
{
private int number;
public Triples()
{
this(0);
}
public Triples(int num)
{
number = num;
}
public void setNum(int num)
{
number = num;
}
private int greatestCommonFactor(int a, int b, int c)
{
for(int n = 0; n <= number; n++)
{
if()
}
return 1;
}
public String toString()
{
String output="";
int max = number;
for(a = 1; a <= max; a++)
{
for(b = a +1; b <= max; b++)
{
for(c = b + 1; c <= max; c++)
{
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
}
}
}
}
return output+"\n";
}
}
UPDATE
Here is my new coding for the same lab:
import static java.lang.System.*;
public class Triples
{
private int number;
public Triples()
{
this(0);
}
public Triples(int num)
{
number = num;
}
public void setNum(int num)
{
number = num;
}
private int greatestCommonFactor(int a, int b, int c)
{
for(int n = 0; n <= number; n++)
{
int max = number;
for(a = 1; a <= max; a++)
{
a = n;
for(b = a +1; b <= max; b++)
{
b =n;
for(c = b + 1; c <= max; c++)
{
c = n;
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
{
if(a%2<=1 && b%2<=1 && c%2<=1)
{
return 1;
}
}
}
}
}
}
}
return 1;
}
public String toString()
{
String output="";
output = greatestCommonFactor(a, b, c);
return output+"\n";
}
}
You can use Euclid's algorithm to calculate the GCD of a and b. Call the result d. Then the GCD of a, b, and c is the GCD of c and d; for that, you can use Euclid's algorithm again.
Here's a brute-force way if you don't care about efficiency:
private int greatestCommonFactor(int a, int b, int c)
{
limit = Math.min(a, b);
limit = Math.min(limit, c);
for(int n = limit; n >= 2; n--)
{
if ( (a % n == 0) && (b % n == 0) && (c % n == 0) ) {
return n;
}
}
return 1;
}
Explanation:
You can save some work by only checking up to the minimum of (a, b, c). Any number greater than that definitely won't be a GCD of all 3.
You need to start your loop at n = limit instead of n = 0 and count backwards.
As soon as we come across a number that produces zero remainder for (a, b, c), that must be the GCD.
If nothing is found within the loop, GCD defaults to 1.

How to write a recursive method to return the sum of digits in an int?

So this is my code so far.
public int getsum (int n){
int num = 23456;
int total = 0;
while (num != 0) {
total += num % 10;
num /= 10;
}
}
The problem is that i cant/know how to change this into a recursive method
Im kind of new with recursion and i need some help on implementing this method to change it so its recursive.
Short, recursive and does the job:
int getsum(int n) {
return n == 0 ? 0 : n % 10 + getsum(n/10);
}
Here it is,
//sumDigits function
int sumDigits(int n, int sum) {
// Basic Case to stop the recursion
if (n== 0) {
return sum;
} else {
sum = sum + n % 10; //recursive variable to keep the digits sum
n= n/10;
return sumDigits(n, sum); //returning sum to print it.
}
}
An example of the function in action:
public static void main(String[] args) {
int sum = sumDigits(121212, 0);
System.out.println(sum);
}
public int sumDigits(int n) {
return (n - 1) % 9 + 1;
}
public static int sumOfDigit(int num){
int sum=0;
if (num == 0)
return sum;
sum = num%10 + sumOfDigit(num/10);
return sum;
}
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
System.out.print("Input num : ");
int num=input.nextInt();
int s=sumOfDigit(num);
System.out.println("Sum = "+s);
}
}
Try this:
int getSum(int num)
{
total = total + num % 10;
num = num/10;
if(num == 0)
{
return total;
} else {
return getSum(num);
}
}
int getSum(int N)
{
int totalN = 0;
totalN += (N% 10);
N/= 10;
if(N == 0)
return totalN;
else
return getSum(N) + totalN;
}
public static int digitSum (int n)
{
int r = n%10; //remainder, last digit of the number
int num = n/10; //the rest of the number without the last digit
if(num == 0)
{
return n;
} else {
return digitSum (num) + r;
}}
This works for positive numbers.
public int sumDigits(int n) {
int sum = 0;
if(n == 0){
return 0;
}
sum += n % 10; //add the sum
n /= 10; //keep cutting
return sum + sumDigits(n); //append sum to recursive call
}
import java.util.Scanner;
public class Adder {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
System.out.println();
int number = input.nextInt();
System.out.println("The sum of the digits is " +adder(number));
}
public static int adder(int num){
int length = String.valueOf(num).length();
int first , last , sum;
if (length==1){
return num;
}
else
{
first = num /10;
last = num % 10;
sum = last + adder(first);
}
return sum;
}
}
I see a lot of solutions on here, but not one in which seems as simple as what follows. I've tested it countless times and it works no problem:
public int sumDigits(int n) {
if (n == 0){
return 0;
}
else{
return n%10 + sumDigits(n/10);
}
}
I used recursion method in java for finding the sum of digits of a number
public class recursion_practice {
static int sum(int n) {
int sum = 0;
if (n > 0) {
int d = n % 10;
sum += d;
return sum + sum(n / 10);
} else return 0;
}
public static void main(String[] args) {
int x = 123;
System.out.println(sum(x)); // it will print 6 as 1+2+3=6
}
}
#include <iostream>
int useRecursion(int x);
using namespace std;
int main(){
int n;
cout<<"enter an integer: ";
cin>>n;
cout<<useRecursion(n)<<endl;
return 0;
}
int useRecursion(int x){
if(x/10 == 0)
return x;
else
return useRecursion(x/10) + useRecursion(x%10);
}
I think it's the shortest so far. The input thing is up too you, though.
public static int getSum(int input) { //example: input=246
int sum=0;
if (input%10==input) { //246%10=6;
return input%10; //2%10=2
}
return input%10+getSum((input-input%10)/10); //(246-6)/10=24; 24%10=4
}

Categories

Resources