Method output giving wrong output - java

public class Pow {
public double getAnswer(double a, double b) {
double b2 = 0;
if (b > 0) {
for (int i = 1; i < b; i++) {
a = a * a;
}
return a;
} else if (b < 0) {
int c = 0;
while (c > b) {
a = a * a;
c--;
}
b2 = 1 / a;
}
return b2;
}
}
I need the second part of my method to return the value of a negative power(i.e. 5^-2 = .04), but the output is always 0. The first part of the method works fine from what I have tested. I do have the last curly braces but they just wouldn't fit in the text box on here. Any help/suggestions would be much appreciated!

Running your code does not produce 0 as a result, but there is a bug.
a = a * a squares the number every iteration, so an will be calculated as: a2n-1.
Try accumulating the multiplication in a different variable:
double b2 = 0;
double result = 1;
if (b > 0) {
for (int i = 1; i <= b; i++) {
result *= a;
}
return result;
} else if (b < 0) {
int c = 0;
while (c > b) {
result *= a;
c--;
}
b2 = 1 / result;
}
return b2;

public class Pow {
public double getAnswer(double a, double b) {
double b2 = 0;
if (b > 0) {
for (int i = 1; i < b; i++) {
a = a * a;
}
return a;
} else if (b < 0) {
return getAnswer(a, -b);
}
return 1; // b is 0
}
Your algorithm for (b < 0) was wrong. If b < 0, the calculation is 1 / a^(-b).
Why your parameter b is of type double? What if b is 2.5? I suggest to change the type of b to int or you have to change your algorithm.

As Bohemian♦ said
a = a * a;
squares a each time.
What we want is for a (the base) to be multiplied by itself b (the power) times.
Since the only difference between a to the power of b and a to the power of (-b) is that the latter is the 1 / the former, we can use quite nearly the same code for both negative and positive exponents.
Code:
public double getAnswer(double a, double b) {//a is the base, b is the power
double a2 = 1;
double b2 = 0;
if (b > 0) {//for positive powers
for (int i = 0; i < b; i++) {//a needs to be multiplied by itself (b) times
a2 = a2 * a;
}
return a2;
}
else if (b < 0) {//for negative powers
for (int i = 0; i < -b; i++) {//a still needs to be multiplied by itself (-b) times, but since b is negative, we increment up to the opposite of b
a2 = a2 * a;
}
return 1 / a2;//finally, since the power (b) is negative, we need to return 1 / (a2)
}
}

Related

Can I solve this problem with Dynamic Programming?

How I find among all pairs a and b with a "least common multiple" LCM(a,b) = 498960 and a "greatest common divisor" GDM(a, b) = 12 a pair with minimum sum a + b?
I solved this with O(n^2) time:
public class FindLcmAndGcdClass {
private int findGcd(int a, int b) {
if (a % b == 0) {
return b;
}
return findGcd(b, a % b);
}
private int findLcm(int a, int b, int gcd) {
return (a * b) / gcd;
}
private void run() {
int minSum = Integer.MAX_VALUE;
int foundNumberOne = 0;
int foundNumberTwo = 0;
for (int i = 12; i <= 498960; i += 12) {
for (int j = i; j <= 498960; j += 12) {
int gcd;
if (i < j) {
gcd = findGcd(j, i);
} else {
gcd = findGcd(i, j);
}
int lcm = findLcm(i, j, gcd);
if (gcd == 12 && lcm == 498960 && i + j < minSum) {
minSum = i + j;
foundNumberOne = i;
foundNumberTwo = j;
}
}
}
System.out.println(minSum);
System.out.println(foundNumberOne);
System.out.println(foundNumberTwo);
}
public static void main(String[] args) {
var o = new FindLcmAndGcdClass();
o.run();
}
}
And it executes quite slowly! I guess the problem can be solved with Dynamic Programming. Can anyone help with more fast solution?
I am not sure if this question can be solved with dynamic programming, but I think of a solution with time complexity O(sqrt(LCM * GCD)).
It is well known that for any two integers a and b, LCM(a, b) * GCD(a, b) = a * b. Therefore, you can first calculate the product of the gcd and lcm, (which is 5987520 in this question). Then for all its factors under sqrt(LCM * GCD), let a be one of the factors, then b = LCM * GCD / a. Test if gcd(a, b) = the required gcd, if so calculate the sum a + b, then find the minimum among the sums, and you are done.

Finding value for ABC

class Main {
public static void main(String[] args) {
int abc;
int total = 1000;
for (abc = 220000000; abc < 240000000; abc++) {
String string1 = Integer.toString(abc);
int a, b, c;
a = 0;
b = 0;
c = 0;
int a2 = squared(a);
int b2 = squared(b);
int c2 = squared(c);
a = Integer.parseInt(string1.substring(0, 3));
b = Integer.parseInt(string1.substring(3, 6));
c = Integer.parseInt(string1.substring(6, 9));
if (a < b && a < c && b < c && a2 < b2 && b2 < c2 && a + b + c == total) {
System.out.println("The answer is " + abc);
} else {
System.exit(0); // testing
}
}
}
public static int squared(int x) {
return (x * x);
}
}
This is my code. I am trying to have the program print the value of abc so that a is less than b which is less than c. And where a squared is less than b squared which is less than c squared. Also, a+b+c must equal 1000. I tried making abc one whole value and using substrings to differ between a, b, and c. An example would be like 224,356,446. An with the substrings it would make a=224, b=356, and c=446. When I run the program, nothing is being printed. The else statement is being invoked because the system exits. Can anyone help?
You print nothing because you do not have a match on your first iteration. The lack of a match fires System.exit(0) so the program exits without another iteration.
You have appeared to make the assumption that that a, b, c are non-negative integers so I'll adopt that same assumption. As such, if a < b < c then a^2 < b^2 < c^2 so we do not have to test for the latter condition.
If a + b + c == 1000 and a < b < c then if a==0 and b==1 (their minimum values) then c == 999. So we know we do not have to iterate beyond 999 in any case. This bound could be further optimized a bit but doing so is pointless since he output operation far outweighs the iteration cost.
public static void main(String[] args) {
int count = 0;
for (int a = 0 ; a < 999 ; ++a) {
for (int b = a+1 ; b < 999 ; ++b) { // a < b
int c = 1000 - a - b;
if (c <= b) {
break;
}
System.out.printf("%d %d, %d, %d", ++count, a, b, c).println();
}
}
}

How to add power function to sigma

I've written this code that computes the sum of the positive divisors, and all the values have to be to the power of a.
For instance:
sigma(0,14) = 1^0 + 2^0 + 7^0 + 14^0 = 4;
sigma(2,12) = 1^2 + 2^2 + 3^2 + 4^2 + 6^2 + 12^2 = 210.
sigma(a, b).
I have tried different versions but I don't know how to add the power function.
try {
int a = Integer.parseInt(input1.getText());
int b = Integer.parseInt(input2.getText());
int result1 = 0;
for (int i = 2; i <= Math.sqrt(b); i++)
{
if (b % i == 0)
{
if (i == (b / i))
result1 += i;
else
result1 += (i + b / i);
}
}
result.setText(String.valueOf(result1 + b + 1));
}
}
In Java the ^ character means XOR.
The power function is provided by the Math.pow() method.
So 3^2 would be Math.pow(3, 2).
If you wanted to implement it yourself for integers, you could do it simply like this:
double power(int a, int b) {
int pow = (b < 0) ? -b : b;
double result = 1;
for (int i = 0; i < pow; i++) {
result *= a;
}
return (b < 0) ? 1 / result : result;
}
But I wouldn't do it myself. It gets a bit more complicated for floating points, and Java has a native underlying implementation which is much faster.
IntStream delivers beautiful concise calculation.
static int sigma(int exp, int num) {
IntStream.rangeClosed(1, num) // 1, ..., num
.filter(k -> num % k == 0) // Only divisors
.map(k -> pow(k, exp))
.sum();
}
static int pow(int k, int exp) {
if (exp == 0) {
return 1;
}
int squareRoot = pow(k, exp/2);
int n = squareRoot * squareRoot;
return (exp % 2) == 0 ? n : n*k;
}
The power calculation can be optimized by not using exp# multiplications of k but square roots.
For those interested in program transformation:
pow(k, exp) needs only to rely on exp with recursion to exp/2 (integer division). So you could turn the code inside out, have a vector of divisors,
and operate on that.
If you want to implement it without using Math.pow() you can simply follow the mathematical definition of the exponentiation for a positive exponent:
public static long exp(int a, int b){ //computes a^b
long result = 1;
for (int i = 0; i < b; i++) {
result *= a;
}
return result;
}
I would recommend that you use Java lambdas to accomplish what you're looking for.
Taking an input and returning a List of positive divisors seems useful on its own.
Raising every entry to a power could be done easily with a lambda.
Keep the two functions separate. Take a more functional approach.
Here is a simple code for you:
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
List<Integer> listOfBs = new ArrayList<>();
System.out.println("Input your a");
int a = scanner.nextInt();
System.out.println("Input your b");
int b = scanner.nextInt();
int sqrt = (int) Math.sqrt(b);
for (int i = 1; i <= sqrt; i++) {
if (b % i == 0) {
listOfBs.add(i);
int d = b / i;
if (d != i) {
listOfBs.add(d);
}
}
}
int sigma = 0;
for(int e : listOfBs)
{
sigma += Math.pow(e,a);
}
System.out.println("Your sigma function is: "+sigma);
}
}

Reducing negative fraction

So i have a little problem with reducing a negative fraction
This is my reduce code
private void reduce() {
int g = Helper.gcd(this.num, this.den);
num /= g;
den /= g;
}
For example:
8/64 gives 1/8
But giving -8/64 let's the program crash
This is my gcd code
public static int gcd(int a, int b) {
while (a != b) {
if (a > b) {
a -= b;
} else {
b -= a;
}
}
return a;
}
You need to extract the sign first.
private void reduce() {
boolean neg = (num < 0) != (den < 0);
num = Math.abs(num);
den = Math.abs(den);
// obtain the GCD of the non-negative values.
int g = Helper.gcd(num, den);
num /= g;
den /= g;
if (neg) num *= -1;
}
Your gcd method only works for positive numbers. Negative numbers and zero need to be handled separately.
public static int gcd(int a, int b) {
a = Math.abs(a);
b = Math.abs(b);
if (a == 0) {
if (b == 0)
throw new IllegalArgumentException();
return b;
}
if (b == 0)
return a;
// The rest is just your code, unchanged.
while (a != b) {
if (a > b) {
a -= b;
} else {
b -= a;
}
}
return a;
}

Code for finding pythagorean triplets

I am currently attempting this question :
A Pythagorean triplet is a set of three natural numbers, a, b and c, for which
a2 + b2 = c2.
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
My code is as follows, I think it should be correct, but the site is telling me my answer is wrong? Can someone help me see the flaws in my logic please?
public class Pythagoras {
public static void main(String[] args) {
int sum = 1000;
int a;
int product=0;
for (a = 1; a <= sum/3; a++)
{
int b;
for (b = a + 1; b <= sum/2; b++)
{
int c = sum - a - b;
if ( c > 0 && (a*a + b*b == c*c) )
System.out.printf("a=%d, b=%d, c=%d\n",a,b,c);
product = a * b * c;
}
}
System.out.println(product);
}
}
Here are 5 solutions (from slow to fast):
1) Trivial implementation - 732857 microseconds (0.7 seconds)
private static void p1(int sum) {
for (int a = 0; a <= sum; a++) {
for (int b = 0; b <= sum; b++) {
for (int c = 0; c <= sum; c++) {
if (a < b && b < c && a + b + c == sum
&& (c * c == a * a + b * b)) {
System.out.print(a * b * c);
return;
}
}
}
}
}
2) Limit the lower bound for b & c (establish the order relation) - 251091 microseconds (0.2 seconds)
private static void p2(int sum) {
for (int a = 0; a <= sum; a++) {
for (int b = a + 1; b <= sum; b++) {
for (int c = b + 1; c <= sum; c++) {
if (a + b + c == sum && (c * c == a * a + b * b)) {
System.out.print(a * b * c);
return;
}
}
}
}
}
3) Limit the lower & upper bounds for b & c - 111220 microseconds (0.1 seconds)
private static void p3(int sum) {
for (int a = 0; a <= sum; a++) {
for (int b = a + 1; b <= sum - a; b++) {
for (int c = b + 1; c <= sum - a - b; c++) {
if (a + b + c == sum && (c * c == a * a + b * b)) {
System.out.print(a * b * c);
return;
}
}
}
}
}
4) Limit lower & upper bounds for b and fix value for c - 2625 microseconds
private static void p4(int sum) {
for (int a = 0; a <= sum; a++) {
for (int b = a + 1; b <= sum - a; b++) {
int c = sum - a - b;
if (c > b && c * c == a * a + b * b) {
System.out.print(a * b * c);
return;
}
}
}
}
5) Use Euclid's formula - 213 microseconds
private static void p5(int sum) {
// a = m^2 - n^2
// b = 2mn
// c = m^2 + n^2
int a, b, c;
int sqrt = (int)Math.sqrt(sum);
for (int n = 1; n <= sqrt; n++) {
for (int m = n+1; m <= sqrt; m++) {
a = m*m - n*n;
b = 2*m*n;
c = m*m + n*n;
if ( a + b + c == 1000 ) {
System.out.print(a * b * c);
return;
}
}
}
}
I think you're missing a set of braces. The indentation leads me to believe the two innermost statements go together but you need curly braces for that to be correct.
if ( c > 0 && (a*a + b*b == c*c) )
{
System.out.printf("a=%d, b=%d, c=%d\n",a,b,c);
product = a * b * c;
}
Without the braces product will always contain the product of the last values of a, b, and c. (333 * 500 * 167 == 27805500).
Though others have already given specific fixes for you code, here's a more general hint that will be useful on other problems as well. Test your code on a simpler version of the problem.
For example, see if your program can find 6,8,10 as a triplet with a sum of 24. With a smaller test you can actually step through the code to see where it's going wrong.
You may try it this way,
public class Pythagoras {
public static void main(String[] args) {
int m = 1, n = 0, a = 0, b = 0, c = 0, sum = 0;
int product = 0;
for (m = 2; m < 100; m++) {
for (n = 1; n < 100; n++) {
while (m > n) {
a = (m * m) - (n * n);
b = (2 * m) * n;
c = (m * m) + (n * n);
sum = a + b + c;
if (sum == 1000) {
product = a * b * c;
System.out.print("a :" + a + "b :" + b + "c : " + c);
System.out.println("Product is" + product);
break;
}
break;
}
}
}
}
}
This implements the Euclid's formula for generating Pythagorean triplet as explained here
Note that in this method we make only triplets hence unwanted repetitions are reduced.
and the output is a :375 b :200 c : 425 Product is 31875000
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public javax.swingx.event.*;
public class Triplet extends JApplet implements ActionListener
{
JLabel l1, l2, l3;
JButton b1;
JTextFiel t1, t2;
public void init()
{
Container c = getContentPane();
c.setLayout(new FlowLayout());
l1=new JLabel("Enter the value of a: ");
l2=new JLabel("Enter the value of b: ");
t1 = new JTextField(20);
t2 = new JTextField(20);
b1=new JButton("Ok");
l2=new JLabel(" ");
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(l3);
b1.addActionListener(this);
public void ActionPerformed(ActionEvent e)
{
int a = Integer.parseInt(t1.getText());
int b = Integer.parseInt(t2.getText());
long c = Math.sqrt(a*a + b*b);
l3.setText(" " +c);
}
}
}
public class Pythagorean_Triplets
{
public static void main(long n)
{
long h=1,p=1,b1;
double b;
while(h<=n)
{
while(p<h)
{
b=Math.sqrt((h*h)-(p*p));
if(b%1==0)
{
b1=(long)b;
System.out.println(b1+","+p+","+h);
break;
}
p++;
}
h++;
p=1;
}
}
}

Categories