Finding value for ABC - java

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();
}
}
}

Related

Method output giving wrong output

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)
}
}

Java for loop is hard to understand

May someone explain to me why the following blocks of code generate such different outputs?
public class hello
{
public static void main(String args[])
{
int a,b,c;
for (a = 0; a < 5; a++)
{
for (b = 4; b >= a; b--)
{
System.out.print(" ");
}
for (c = 0; c <= a - b; c++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Output:
public class hello
{
public static void main(String args[])
{
int a,b,c;
for (a = 0; a < 5; a++)
{
for (b = 4; b >= 0; b--)
{
System.out.print(" ");
}
for (c = 0; c <= a - b; c++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Output:
Shouldnt the outputs be the same since b >= a is equivalent to b >= 0 as b's value will be deducted by 1 for every loop?
No, the outputs cannot be the same, since every time you are executing
for (a = 0; a < 5; a++)
this gets executed as well (5 times)
for (b = 4; b >= a; b--)
{
System.out.print(" ");
}
But the value of a is changing with every iteration: a will be initially 0, then 1, 2, 3 and finally 4.
Hence, the number of spaces that you are printing in the first scenario will decrease with every iteration of a.
For a = 0 we have:
b = 4,
b = 3,
b = 2,
b = 1,
b = 0 (for loop stops since b=-1 is not >= a=0)
For a = 1 we have:
b = 4,
b = 3,
b = 2,
b = 1 (for loop stops since b=0 is not >= a=1)
For a = 2 we have:
b = 4,
b = 3,
b = 2 (for loop stops since b=1 is not >= a=2)
For a = 3 we have:
b = 4,
b = 3 (for loop stops since b=2 is not >= a=3)
For a = 4 we have:
b = 4 (for loop stops since b=3 is not >= a=4)
variable a will go from 0 to 4, so for each iteration you will have:
for (b = 4; b >= 0; b--)
{ [...]
for (b = 4; b >= 1; b--)
{ [...]
for (b = 4; b >= 2; b--)
{ [...]
Please read the comments in the code and you will se the difference!
int a, b, c;
for (a = 0; a < 5; a++)
{
for (b = 4; b >= a; b--) // Print every time b-a + 1 underscores... since you start every time with b=4 you have for each a one space fewer
{
System.out.print(" ");
}
for (c = 0; c <= a - b; c++) // and then print (a-b)-c +1 stars (b is every time a-1)...
// (first a=0 -b=-1)+1=2 and any time it will prit 2 stars scince
{
System.out.print("*");
}
System.out.println();
}
for (a = 0; a < 5; a++)
{
for (b = 4; b >= 0; b--) // Print every time b-a + 1=4 underscores
{
System.out.print(" ");
}
for (c = 0; c <= a - b; c++) // and then print (a-b)-c +1 stars (b is every time -1)...
// first time ( a=0 -b=-1)+1 =2 , second time (a=1 - b=-1)+1=3
{
System.out.print("*");
}
System.out.println();
}

Program to find pythogorean triplet whose sum is 1000, cannot figure out why it doesn't work?

import java.util.*;
public class Euler9
{
public static void main (String[] args)
{
double a=3, b=4, c=5;
double pdt=0;
int i;
for(i=0;i<=500000;i++)
{
if ((a*a)+(b*b)==(c*c))
{
System.out.println("a = "+a+" b = "+b+" c = "+c+" is a pyth tripl.");
if ((a+b+c)==1000.0)
{
pdt=a*b*c;
break;
}
}
a++;
b++;
c++;
}
System.out.println(pdt);
}
}
Hey, I've been trying to do a few Euler problems for a class I'm taking, and this is my solution is Euler9, https://projecteuler.net/problem=9 but for some reason I cannot get this code to work. Regardless of the value I set i to it seems to end after a single iteration and I cannot figure out why for the life of me. Thanks for the help.
You could reduce your code a lot if you did something like this using multiple for loops, also I don't think this task requires the use of double or importing java.util.*; when you are not using it at all:
class Euler9 {
public static void main(String[] args) {
int sum = 1000;
for(int a = 1; a <= sum/3; a++) {
for (int b = a + 1; b <= sum/2; b++) {
int c = sum - a - b;
if (a*a + b*b == c*c) {
System.out.format("a=%d, b=%d, c=%d\n", a, b, c);
}
}
}
}
}
Output:
a=200, b=375, c=425
You are incrementing a, b, c all at the same time.
In essence, you're only tring out
3^2 + 4^2 = 5^2
4^2 + 5^2 = 6^2
5^2 + 6^2 = 7^2
6^2 + 7^2 = 8^2
...
100^2 + 101^2 = 102^2
and so on...
While brute-force algorithm (simply trying every option possible) is not the best approach, you might want to try incrementing a,b,c in separate loops if you want to stick to your approach.
You can't increment all of them at once. You could do something like
for(int a = 0; a < 100; a++)
for(int b = 0; b < 100; b++)
for(int c = 0; c < 100; c++)
if(a^2 + b^2 == c^2)
...

Hackerrank: Sherlock and Anagrams(Moderate under Strings section)

Problem description: https://www.hackerrank.com/challenges/sherlock-and-anagrams
Can somebody please tell me what am I doing wrong? My algorithm is:
Input the string ; str
Generate a pattern string from length i=1 to str.length-2
Check whether anagram of pattern string exist in str.substring(i+1)
Below are the test cases which are NOT passing :
input-string My OP Expected OP
ifailuhkqq 2 3
My code:
public class SherlockandAnagrams
{
static int count = 0;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
generatePairs(sc.next());
int len = 1;
}
public static void generatePairs(String str)
{
int len = 1;
//int i=0;
while (len < str.length())
{
for (int i = 0; i + len <= str.length(); i++)
findAnagramPairs(str, len, str.substring(i, i + len), i + 1);
len++;
}
System.out.println(count);
}
private static void findAnagramPairs(String str, int len, String pattern, int p)
{
int i = p;
while (i + len <= str.length())
{
if (checkAnagram(pattern, str.substring(i, i + len)))
{
count++;
}
i++;
}
}
private static boolean checkAnagram(String pattern, String text)
{
if (pattern.length() == 1)
{
if (pattern.equals(text))
return true;
else
return false;
}
else
{
int i = 0;
int j = pattern.length() - 1;
while (i < pattern.length())
{
if (pattern.charAt(i) == text.charAt(j))
{
i++;
j--;
}
else
return false;
}
return true;
}
}
}
A simpler solution to the problem would be the following:
An anagramic pair with starting-indices at (n , m) and length l can only exist, if another pair with length l - 1 at (n or n - 1 or n + 1 , m or m - 1 or m - 1) exists. Thus we can easily reduce efficiency from bruteforce to a more efficient solution.
An example:
A B C B A A B C A
len 1 A A A A //all pairs containing A
len 2 A B B A //all pairs that match A B or its reverse
len 3 A B C B A //all pairs that match A B C or its reverse
OR
A B C B A A B C A
len 1 B B B //all pairs containing B
len 2 B C B B C //all pairs that match B C or its reverse
len 3 A B C B A A B C //all pairs that match A B C or its reverse
The same applies to any other pair of length l and it's matching pairs with length l + 1. In general, a pair of length l + 1 only exists, if two pairs (a , b) and (c , d) of length l exists, such that either a = c - l and b = d + l or a = c + l and b = d - l exist.
In pseudocode this would look like this:
set pairs = listAnagrams(input , 1)
int len = 1
while NOT pairs.isEmpty()
set next_len
//generate pairs with length len + 1
for pair p in pairs
pair left = pair(p.a - len , p.b + len)
pair right = pair(p.a + len , p.b - len)
if pairs.contains(left)
next_len.add(pair(p.a , left.b)
if pairs.contains(right)
next_len.add(pair(left.a , p.b)
pairs = next_len
++len

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