I've been having some issues trying to solve this code that my professor sent to me for studying purposes. I usually can solve the isPrime and getPrime no problem but my issue lies with the gcd class. Would love to get some input on this. Thanks :) Sorry for the formatting since i'm new to the site
import java.util.*;
public class Util3
{
public ??? getSmaller(???)
{
int smaller;
if (???)
smaller = ???;
else
smaller = ???;
return smaller;
}
public ??? gcd(??? a, ??? b)
{
int g, smaller;
smaller = ???(a, b);
g = smaller;
for (int i = ???; i >= 1; i++) { // from smaller to 1
if (a % i == 0 ??? ???) {
g = i;
???;
}
}
return g;
}
public ??? isPrime(int p)
{
if (p < 2)
return false;
int i;
for (i = ???; i <= ???; i++) // from 2 to p-1
if (??? == 0) // if p is divisible by i
break;
if (i == ???)
return ???;
else
return ???;
}
public ??? getPrime(int n)
{
boolean b;
int p;
for (p = n+1; ; p++) { // n+1, n+2, ...
b = ???(p); // check if p is a prime number
if (???)
break;
}
return p;
}
}
You can use a naive solution:
public static int gcd(int a, int b) {
int current_gcd = 1;
for(int d = 2; d <= a && d <= b; ++d) {
if (a % d == 0 && b % d == 0) {
if (d > current_gcd) {
current_gcd = d;
}
}
}
return current_gcd;
}
Or a recursive one:
public static int GCD(int a, int b) {
if (b == 0) {
return a;
}
}
return GCD(b, a % b);
}
Related
This question has been answered here.
My query is, following approach-1 works, however the variation of it, that is approach-2 does not, rather it gives time limit exceeded. I can not find out why. I used interviewbit portal to solve this question, and here it is in leetcode.
The issue is
for(; i<32 && ((B<<i)-A <=0); i++) {
}
works, but
for(; i<32 && (B<<i)<=A; i++) {
}
does not work, rather gives Time Limit Exceeds issue.
Approach-1
public class Solution {
public int divide(int A, int B) {
//Base Cases
if (B == 1) {
return A;
}
if (A == Integer.MIN_VALUE && B == -1) {
return Integer.MAX_VALUE;
}
boolean neg = false;
if((A<0 && B>0) || (A>0 && B<0)) neg=true;
A = A==Integer.MIN_VALUE ? Integer.MAX_VALUE : Math.abs(A);
B = Math.abs(B);
if(A<B) return 0;
int res=0;
while(A>=B) {
int i=0;
for(; i<32 && ((B<<i)-A <=0); i++) {
}
i--;
res+=(1<<i);
A-=(B<<i);
}
return neg? res*-1 : res;
}
}
Approach-2
public class Solution {
public int divide(int A, int B) {
//Base Cases
if (B == 1) {
return A;
}
if (A == Integer.MIN_VALUE && B == -1) {
return Integer.MAX_VALUE;
}
boolean neg = false;
if((A<0 && B>0) || (A>0 && B<0)) neg=true;
A = A==Integer.MIN_VALUE ? Integer.MAX_VALUE : Math.abs(A);
B=Math.abs(B);
if(A<B) return 0;
int res=0;
while(A>=B) {
int i=0;
for(; i<32 && (B<<i)<=A; i++) {
}
i--;
res+=(1<<i);
A-=(B<<i);
}
return neg? res*-1 : res;
}
}
It was an interview question and I was asked to fix the code-->
Given a sorted array, I have to find the array index of the element if it is present, else I have to return -1. Following is my code:
public static int returnIndex(int[] a, int x) {
int n = a.length;
if (n == 0) {
return -1;
}
int l = 0;
int r = n - 1;
while (l < r) {
int m = (l + r) / 2;
if (a[m] > x) {
r = m - 1;
} else {
l = m;
}
}
if (a[l] == x) {
return l;
}
return -1;
}
Code works fine if I have to find the middle element but fails (goes into infinite loop) when I have to find any other element. Can anyone point out the mistake?
I am allowed to make only 3 modifications in this code.
Worst case Time Complexity-O(log(n))
Worst case Space Complexity-O(1)
You are trying binary search here. So you need to have 3 conditions. midValue > key, midValue < key and midValue == key. You are handling only 2. Also when midValue > key you need to add one to index. So modify your method like
public static int returnIndex(int[] a, int x) {
int n = a.length;
if (n == 0) {
return -1;
}
int l = 0;
int r = n - 1;
while (l < r) {
int m = (l + r) / 2;
if (a[m] > x) {
r = m - 1;
} else if(a[m] < x){
l = m + 1;
} else {
return m;
}
}
return -1;
}
If you are not doing it for an exercise you could achieve the same via Arrays.binarySearch() method.
I would it this way:
public static int returnIndex(int[] a, int x) {
int n = a.length;
if (n == 0) {
return -1;
}
int l = 0;
int r = n - 1;
while (l < r) {
int m = (l + r) / 2;
if (a[m] == x) {
return m;
}
if (a[m] > x) {
r = m - 1;
} else {
l = m + 1;
}
}
return -1;
}
I have completed this exercise on codingbat successfully, but I want to know is there a better/faster or more elegant solution?
Given 3 int values, a b c, returns their sum. However, if one of the values is the same as another of the values, it does not count towards the sum.
loneSum(1, 2, 3) → 6
loneSum(3, 2, 3) → 2
loneSum(3, 3, 3) → 0
public int loneSum(int a, int b, int c)
{
int sum = a + b + c;
if ( a == b) { sum = sum - a - b; }
if ( a == c) { sum = sum - a - c; }
if( b == c) { sum = sum - b - c; }
if (( a == b ) && (b==c)) { sum = 0; }
return sum;
}
Maybe this code?
public static int loneSum(int a, int b, int c) {
if (a == b && b == c) {
a = 0;
b = 0;
c = 0;
}
if (a == b) {
a = 0;
b = 0;
}
if (a == c) {
a = 0;
c = 0;
}
if (b == c) {
b = 0;
c = 0;
}
return a + b + c;
}
You can measure the time ... this seems like less sub ops so might be faster
public int loneSum(int a, int b, int c) {
int sum = 0;
boolean ab = a != b;
boolean ac = a != c;
boolean bc = b != c;
if(ab && ac) sum += a;
if(ab && bc) sum += b;
if(bc && ac) sum += c;
return sum;
}
public int loneSum(int a, int b, int c) {
if ( (a==b) && (b==c) && (c==a) ) return 0;
else
{
if (a==b) return c ;
if (b==c) return a;
if (a==c) return b;
else return a+b+c;
}
}
public int loneSum(int a, int b, int c) {
int sum = a+b+c;
if (a==b) sum -= a*2;
if (b==c) sum -= b*2;
if (c==a) sum -= c*2;
if (sum<0) sum=0;
return sum;
}
This take 4 comparisons.
Initialize sum to a+b+c
Compare numbers to each other and if same, decrease sum by num*2.
If multiple IF's are hit (meaning a==b==c), the sum becomes 0. Return 0 in that case.
if (a==b && b==c) return 0;
if (a==b) return c;
if (a==c) return b;
if (b==c) return a;
return a+b+c;
def lone_sum(a, b, c):
sum=0
if a==b==c:
sum=0
elif a==b:
sum=c
elif a==c:
sum=b
elif b==c:
sum=a
else:
sum=a+b+c
return sum
This is for python
public int loneSum(int a, int b, int c)
{
int sum = a + b + c;
if ( a == b) { sum = c; }
if ( a == c) { sum = b; }
if( b == c) { sum = a; }
if (( a == b ) && (b==c)) { sum = 0; }
return sum;
}
This is for java
I sending you another approach using ternary operators. I hope it can be useful in your exercises and learning process.
public int noTeenSum(int a, int b, int c) {
a = (a >= 13 && a <= 19) ? (a == 15 || a == 16) ? a : 0 : a;
b = (b >= 13 && b <= 19) ? (b == 15 || b == 16) ? b : 0 : b;
c = (c >= 13 && c <= 19) ? (c == 15 || c == 16) ? c : 0 : c;
return a+b+c;
}
I think this is easier to read
def lone_sum(a, b, c):
if a == b == c:
return 0
if a == b:
return c
if b == c:
return a
if a == c:
return b
else:
return a + b + c
Here's my answer:
def lone_sum(a, b, c):
if a!=b and b!=c and c!=a:
return a+b+c
elif a==b==c:
return 0
elif a==b:
return c
elif b==c:
return a
elif c==a:
return b
public int loneSum(int a, int b, int c) {
int sum = a+b+c;
if(a==b)
sum -= (a+b);
if(a==c)
sum -= (a + c);
if(b==c)
sum -= (b+c);
return sum > 0? sum: 0;
}
def lone_sum(a, b, c):
tempSum, arr2 = a+b+c, list(set([a,b,c]))
if (a==b==c): return 0
return sum(arr2) - (tempSum - sum(arr2))
Please see the below function :
def su(a,b,c):
total=0
for x in (a,b,c):
if x==(x+1):
y=0
else:
y=1
total+=x*y
return total
print(su(3,2,3))
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));
}
}
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.