I want to get two numbers whose product is equal to a given number. Below is my code but it throws an ArrayIndexOutOfBoundsException and I don't know why.
package com.sample;
public class ProductCheck {
public static void main(String[] args) {
// TODO Auto-generated method stub
int numArray[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int temp = numArray[0];
for (int i = 0; i <= numArray.length; i++) {
if (temp * numArray[i + 1] == 27) {
System.out.println("The two numbers are " + temp + " and " + numArray[i + 1]);
} else {
temp = numArray[i + 1];
}
}
}
}
In this case it should print 3 and 9 as the product of these two numbers is equal to 27, but it doesn't work. Could anybody please point out why? Thanks in advance.
Your algorithm is incorrect, because it would never find a pair unless its members are at adjacent indexes. In other words, if you look, say, for 30, it would find 5 and 6, because they are next to each other; however, it wouldn't find 3 and 9, because there are other numbers between them.
To solve this problem correctly, you need two nested loops: one to pick the first number, and the other one to pick the second number to be multiplied. Then you would check the product in the inner loop, and print the result if the match is found.
for (int i = 0 ; i != numArray.length ; i++) {
for (int j = i+1 ; j != numArray.length ; j++) {
// Use i and j as indexes of the two numbers to be multiplied.
// Do your checking here, and print the result.
}
}
Note: You get ArrayIndexOutOfBoundsException because your loop condition is incorrect: the loop should stop when you reach numArray.length-1, because you access numArray[i + 1].
The exception occurs because your i loops from 0 to numArray.length, which is 10. But as you may know, arrays are zero based, so the largest index is 9. Putting 10 in there will certainly throw an exception. Looping to numArray.length - 1 doesn't work either because you are accessing i + 1, which will be 10 again. So you need numArray.length - 2 for it to not throw an exception.
Not throwing an exception doesn't mean it outputs the right thing though. You seem to be only looking at number pairs like (4,5), (5,6) etc. You will never check 3,9 like this.
Another approach is to output as soon as you find a number that is divisible by 27:
for (int i = 2 ; i < 27 ; i++) {
if (27 % i == 0) {
System.out.println("Found the two numbers: " + i + " and " + 27 / i);
break;
}
}
Related
Suppose I have one list which always has the count of even number. Now I want to segregate the list with different group indexes with below conditions,
1) First element (1st element) with one index (EX: 1)
2) Next two elements with same index (Ex: 2nd, 3rd element with index 2,
4th and 5th element with index 3)
3) Last element(6th element) with index 4
I tried with nested for loops to achieve the same, but didn't get the expected output.
Any help is appreciated.
Sample Input:
[2,3,53,52,33,12,44,66]
Sample Output:
2 - 1
3 - 2
53 - 2
52 - 3
33 - 3
12 - 4
44 - 4
66 - 5
I have implemented this using the two additional variables z and count, I am
incrementing z only if the count%2 is 0, and at-last we need to check if the
size-1 is equal to the i variable for the third condition.
Also, for the first condition I am printing the arraylist value at first index and z variable value at i iff the i counter value is 0.
Please see the below code that I have simulated for your input list that I
have added manually ! Please use the link to test :
http://rextester.com/ESYF23501
import javafx.collections.ArrayChangeListener;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> a= new ArrayList<Integer>();
a.add(2);
a.add(3);
a.add(53);
a.add(52);
a.add(33);
a.add(12);
a.add(44);
a.add(66);
int i = 0;
int z = 2;
//Count to group the middle number by checking its value with respect to mod 2
int count = 0;
for(i = 0; i < a.size(); i++)
{
if(i == 0 )
{
z = i+1;
System.out.println(""+a.get(i)+" " + "" +z+"" );
}
if(i > 0 && i != (a.size() -1))
{
//Increament z if the count is even so that we print the group for two times
if(count%2 == 0)
{
z++;
}
System.out.println(""+a.get(i)+"" +" "+ ""+z+"" );
count ++;
}
if(i == a.size() -1 )
{
z++;
System.out.println(""+a.get(i)+"" +" "+ ""+z+"" );
}
}
}
}
This should work correctly if I understood your question right:
System.out.println(elements.get(0) + " - 1"); // Prints the first number, which has the value of 1
int value = 2; // Value corresponding to the number
for (int i = 1; i < elements.size(); i++) { // Loops through the list starting at second element (index of 1)
System.out.println(elements.get(i) + " - " + value); // Prints the number and the value
if (i % 2 == 0) value++; // Increases the value every two loops
}
It starts by printing out the first number and 1, which as you described always corresponds to each other. Then it loops through the list of numbers starting at the second number (i = 1), and prints out each number and the corresponding value. The value increases every two loops, which is every time the loop number is divisible by 2 (i % 2).
I'm new to java. This is a question about if block in a for loop. This code is from a algorithm practice.
The code is to take an int array but treat it as an integer and add one to this integer, and convert the new integer back to array format. if I didn't describe it clearly, please refer to the original here.
public static int[] plusOne(int[] digits) {
int size = digits.length;
for(int i=size-1; i>=0; i--) {
if(digits[i] < 9) {
System.out.println("tag1 digits.i = " + digits[i]);
digits[i]++;
System.out.println("tag2 digits.i = " + digits[i]);
return digits; // <-- return
}
System.out.println("tag3 digits.i= " + digits[i]);
digits[i] = 0; //?
System.out.println("tag4 digits.i= " + digits[i]);
}
int[] intOut = new int [size+1];
intOut[0] = 1;
return intOut;
}
In the codes above, I added some println() to show how digit[i] changes.
When the input is {1,2,3}, why the line of digits[i] = 0 doesnt work? Reading the code I thought all int in int[] digits will be set to 0.
If it return in the if block, does it mean stop the current iteration and ignore the rest code in the for loop after the if block?
update I failed to describe it clearly.My question was not on what and how to accomplish with the code, but about given the input i mentioned, why the code after if statement doesn't work. And now i learnt that the return statement at the last line of the if block means to do it(stop current iteration). Sorry for this silly question..!
Your code add one to the number passed as digit array.
So when you add 1 to 123, you get 124. The code starts with the last digit, looks whether it is less than 9, then add 1 only to the last digit.
this happens in the if-block. The return ends the function
The code which sets a digit to 0 will only reached when there is some overflow. This overflow can only happen when you pass a number where the last digit is 9.
To reach this case you must pass something like 129 (or {1,2,9}). Then the last digit become 0 and the second last digit is checked. In this case added by one, return 130
To reach the code behind the loop, you have to pass a list where all digits are set to 9. For example 99 (or {9,9}).
In this case, the last digit will set to 0, the first digit will set to 0, then a new list will be generates with one more digit. Initially all digits are set to 0. Then the first digit will be set to 1. This results in 100.
return leaves the function/method
break leaves the surrounding loop (for,while)
So the answer to your question in bold is YES
For the below loop:
for(int i=size-1; i>=0; i--) {
if(digits[i] < 9) {
System.out.println("tag1 digits.i = " + digits[i]);
digits[i]++;
System.out.println("tag2 digits.i = " + digits[i]);
return digits;
}
System.out.println("tag3 digits.i= " + digits[i]);
digits[i] = 0; //?
System.out.println("tag4 digits.i= " + digits[i]);
}
The moment digit[i] < 9 it will go inside the if condition. But after that it will return the digit[] and will come out of the method.
Hence you will never see digit[i] < 9 i.e. 1 to 8 being set to 0.
I have just started learning java in netbeans at university. I have written a code to multiply the numbers between 4 and 30 by 3, so that my code will only print out the numbers >= to 4 and will not exceed 30 when multiplied by 3.
I would like my code to print out there are 7 integers greater or equal....etc but my code prints out there are 11 integers I always get confused as to what I need to write after my for or while loops, I am pretty sure my maths is right but why is it calculating to 11 instead of 7?
public static void main(String[] args) {
int start = 4, stop = 30, multiple = 3;
countMultiples(start,stop, multiple);
}
public static void countMultiples(int start, int stop, int multiple){
int numbers = 0;
for(int i = start; i <=stop; i++)
if(numbers * multiple <= stop)
numbers++;
System.out.println("there are " + numbers + " integers greater or equal " + start + " and not exceeding " + stop);
System.out.println("which multiplied by " + multiple);
}
You have logic mistake at if condition inside for loop you just need to multiply i * multiplein order to get the expected result:
for(int i = start; i <=stop; i++){
if(i * multiple <= stop){
numbers++;
}
}
public static void countMultiples(int start, int stop, int multiple){
int numbers = 0;
for(int i = start; i <=stop; i++) {
if (i * multiple <= stop) { // <-- the numbers should be i
numbers++;
} else {
break;
}
}
}
Basically what you are doing inside the if is
first you are multiplying with the number which starts from 0 and upon multiplication the overall result is <=30 and your if condition satisfies and it increment your count.
*The difference that you are getting in your count is because you are starting from 0 ,but as you mentioned your number should begin from 4.
So instead of
if(numbers * multiple <= stop)
numbers++;
do this
if(i*multiple <=stop)
numbers++;
Since now you start from i which has its initial value as 4, you shoukd get the right count
You missed the logic here if(numbers * multiple <= stop)
Do it like this
for(int i = start; i <=stop; i++)
if(i * multiple <= stop)
numbers++;
okay first thing first, 4 and 30 are not included right ?
so when setting the i add 1 to it.
then in the condition of the loop remove the equal sign , so it will stop before reaching the number 30.
for(int i = start+1 ; i <stop; i++){//start checking from number 5 , remove the equal sign
if(multiple* i < stop){ //also remove the equal sign here
numbers++;
System.out.println(multiple* i+" :there are " + numbers + " integers greater or equal " + start + " and not exceeding " + stop);
}
I am trying to make a prime number list. I have coded it, but it only tells me that the prime numbers of 1 - 100 is 1. I am not sure why that is happening. I also want to make a JFrame for it.
import javax.swing.JOptionPane;
public class ProgrammingAssignment7 {
public static void main(String[] args) {
//Scanner Scan = new Scanner (System.in);
//DECLARE VARIABLES
int x = 1;
int i = 1;
int iNumber = 1;
boolean bNotPrime = false;
boolean bIsPrime = true;
int iNumberToTest;
int iPrimeCheck;
int iCounter;
int iResult = 1;
int iFact = 1;
int iLimit = 100;
String OutputStr = null;
System.out.println("Prime numbers between 1 and " + iLimit);
//loop through the numbers one by one
for(i=1; i < 100; i++) {
bIsPrime = true;
//check to see if the number is prime
for(int j = 2; j < i ; j++) {
if(i % j == 0) {
bIsPrime = false;
break;
}
}
}
// print the number
if(bIsPrime) {
OutputStr = "The Prime Numbers of 1 - 100 are: " + i + "\n";
}
JOptionPane.showMessageDialog(null, OutputStr, "PRIME NUMBERS", JOptionPane.INFORMATION_MESSAGE);
//System.out.print(i + "\n" );
System.exit(0);
}
}
You are calling system.exit(0) in your for loop. So that it will terminate the program after the first iteration. Remove that line and then try to run program. It will give you correct results.
Besides fixing your code you should also fix your algorithm. You are using an algorithm called trial division, which will be uncomfortably slow as your limit increases. Instead, you should use an algorithm called the Sieve of Eratosthenes, invented over two thousand years ago and still widely used today. Here is pseudocode for a simple version of the Sieve of Eratosthenes; I'll leave it to you to translate to Java:
function primes(n)
sieve := makeArray(2..n, True)
for p from 2 to n step 1
if sieve[p]
output p
for i from p * p to n step p
sieve[i] := False
Eratosthenes' algorithm begins by making a list of numbers form 2 to the maximum desired prime n, then enters an iterative phase. At each step, the smallest uncrossed number that hasn't yet been considered is identified, and all multiples of that number, starting from its square, are crossed out; this is repeated until no uncrossed numbers remain unconsidered. All the numbers that remain uncrossed are prime. The inner loop starts at p * p because any smaller composites must have already been crossed out by smaller primes.
For example, to find the primes less than thirty, first report that 2 is prime and cross out 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26 and 28. Then 3 is uncrossed, so report it as prime and cross out 9, 12, 15, 18, 21, 24, and 27. Since 4 has been crossed out, the next uncrossed number is 5, so report it as prime and cross out 25. Finally, since 7 * 7 is greater than 30, the inner loop stops executing and the outer loop collects the rest of the primes: 7, 11, 13, 17, 19, 23 and 29.
If you're interested in programming with prime numbers, I modestly recommend an essay at my blog, which among other things provides an optimized version of the Sieve of Eratosthenes.
In the inner loop, it is enough to iterate to the SQRT(N) instead of N. It can reduces a runtime a bit.
for(int j = 2; j < Math.sqrt(i) ; j++) {
}
Smart algorithm for writing out prime numbers from 1-100 (and also 1- [how many you want] - if you change 100 for another number). Prime numbers can be divisible only by two numbers: 1 and itself, so k have to be equals or less than 2.
for (int i=1; i<=100; i++) {
int k = 0;
for (int j=1; j<=i; j++ ) {
if (i % j == 0) {
k++;
}
}
if (k <= 2) {
System.out.println(i);
}
}
This is the question I've been assigned:
A so-called “star number”, s, is a number defined by the formula:
s = 6n(n-1) + 1
where n is the index of the star number.
Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) star numbers are: 1, 13, 37,
73, 121, 181
In contrast a so-called “triangle number”, t, is the sum of the numbers from 1 to n: t = 1 + 2 + … + (n-1) + n.
Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) triangle numbers are: 1, 3, 6, 10, 15, 21
Write a Java application that produces a list of all the values of type int that are both star number and triangle numbers.
When solving this problem you MUST write and use at least one function (such as isTriangeNumber() or isStarNumber()
or determineTriangeNumber() or determineStarNumber()). Also you MUST only use the formulas provided here to solve the problem.
tl;dr: Need to output values that are both Star Numbers and Triangle Numbers.
Unfortunately, I can only get the result to output the value '1' in an endless loop, even though I am incrementing by 1 in the while loop.
public class TriangularStars {
public static void main(String[] args) {
int n=1;
int starNumber = starNumber(n);
int triangleNumber = triangleNumber(n);
while ((starNumber<Integer.MAX_VALUE)&&(n<=Integer.MAX_VALUE))
{
if ((starNumber==triangleNumber)&& (starNumber<Integer.MAX_VALUE))
{
System.out.println(starNumber);
}
n++;
}
}
public static int starNumber( int n)
{
int starNumber;
starNumber= (((6*n)*(n-1))+1);
return starNumber;
}
public static int triangleNumber( int n)
{
int triangleNumber;
triangleNumber =+ n;
return triangleNumber;
}
}
Here's a skeleton. Finish the rest yourself:
Questions to ask yourself:
How do I make a Triangle number?
How do I know if something is a Star number?
Why do I only need to proceed until triangle is negative? How can triangle ever be negative?
Good luck!
public class TriangularStars {
private static final double ERROR = 1e-7;
public static void main(String args[]) {
int triangle = 0;
for (int i = 0; triangle >= 0; i++) {
triangle = determineTriangleNumber(i, triangle);
if (isStarNumber(triangle)) {
System.out.println(triangle);
}
}
}
public static boolean isStarNumber(int possibleStar) {
double test = (possibleStar - 1) / 6.;
int reduce = (int) (test + ERROR);
if (Math.abs(test - reduce) > ERROR)
return false;
int sqrt = (int) (Math.sqrt(reduce) + ERROR);
return reduce == sqrt * (sqrt + 1);
}
public static int determineTriangleNumber(int i, int previous) {
return previous + i;
}
}
Output:
1
253
49141
9533161
1849384153
You need to add new calls to starNumber() and triangleNumber() inside the loop. You get the initial values but never re-call them with the updated n values.
As a first cut, I would put those calls immediatly following the n++, so
n++;
starNumber = starNumber(n);
triangleNumber = triangleNumber(n);
}
}
The question here is that "N" neednt be the same for both star and triangle numbers. So you can increase "n" when computing both star and triangle numbers, rather keep on increasing the triangle number as long as its less the current star number. Essentially you need to maintain two variable "n" and "m".
The first problem is that you only call the starNumber() method once, outside the loop. (And the same with triangleNumber().)
A secondary problem is that unless Integer.MAX_VALUE is a star number, your loop will run forever. The reason being that Java numerical operations overflow silently, so if your next star number would be bigger than Integer.MAX_VALUE, the result would just wrap around. You need to use longs to detect if a number is bigger than Integer.MAX_VALUE.
The third problem is that even if you put all the calls into the loop, it would only display star number/triangle number pairs that share the same n value. You need to have two indices in parallel, one for star number and another for triangle numbers and increment one or the other depending on which function returns the smaller number. So something along these lines:
while( starNumber and triangleNumber are both less than or equal to Integer.MAX_VALUE) {
while( starNumber < triangleNumber ) {
generate next starnumber;
}
while( triangleNumber < starNumber ) {
generate next triangle number;
}
if( starNumber == triangleNumber ) {
we've found a matching pair
}
}
And the fourth problem is that your triangleNumber() method is wrong, I wonder how it even compiles.
I think your methodology is flawed. You won't be able to directly make a method of isStarNumber(n) without, inside that method, testing every possible star number. I would take a slightly different approach: pre-computation.
first, find all the triangle numbers:
List<Integer> tris = new ArrayList<Integer>();
for(int i = 2, t = 1; t > 0; i++) { // loop ends after integer overflow
tris.add(t);
t += i; // compute the next triangle value
}
we can do the same for star numbers:
consider the following -
star(n) = 6*n*(n-1) + 1 = 6n^2 - 6n + 1
therefore, by extension
star(n + 1) = 6*(n+1)*n + 1 = 6n^2 + 6n +1
and, star(n + 1) - star(n - 1), with some algebra, is 12n
star(n+1) = star(n) + 12* n
This leads us to the following formula
List<Integer> stars = new ArrayList<Integer>();
for(int i = 1, s = 1; s > 0; i++) {
stars.add(s);
s += (12 * i);
}
The real question is... do we really need to search every number? The answer is no! We only need to search numbers that are actually one or the other. So we could easily use the numbers in the stars (18k of them) and find the ones of those that are also tris!
for(Integer star : stars) {
if(tris.contains(star))
System.out.println("Awesome! " + star + " is both star and tri!");
}
I hope this makes sense to you. For your own sake, don't blindly move these snippets into your code. Instead, learn why it does what it does, ask questions where you're not sure. (Hopefully this isn't due in two hours!)
And good luck with this assignment.
Here's something awesome that will return the first 4 but not the last one. I don't know why the last won't come out. Have fun with this :
class StarAndTri2 {
public static void main(String...args) {
final double q2 = Math.sqrt(2);
out(1);
int a = 1;
for(int i = 1; a > 0; i++) {
a += (12 * i);
if(x((int)(Math.sqrt(a)*q2))==a)out(a);
}
}
static int x(int q) { return (q*(q+1))/2; }
static void out(int i) {System.out.println("found: " + i);}
}