Multiplying odd numbers of 1-15 - java

I've written the following code:
int oddProd = 1;
for(int count = 1; count >= 15; count++){
if (count % 2 != 0)
oddProd = oddProd * count;
}
System.out.println("Odd Product: " + oddProd);
Why doesn't this work? It outputs 1, and I checked, it doesn't even enter the for loop!

for(int count = 1; count >= 15; count++){
You have the expression written the wrong way around; it is now count >= 15 but it should be count <= 15.

The middle part of the for loop is the boolean check, and yours will always be false:
count >= 15;
This won't work since it won't be true in the beginning, and your loop won't start. Change the greter than operator to a less than one:
count <= 15;

Related

What is the role of temp = 0 in finding primes?

I have the following code to print all prime numbers from 2 to 100:
int number1 = 2, number2 = 100, temp = 0;
System.out.println("prime numbers between" + number1 + "and" + number2 + "are :");
for (int i = number1; i <= number2; i++) {
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
temp = 1;
break;
} else {
temp = 0;
}
}
if (temp == 0) {
System.out.println(i);
}
}
What is the role of temp = 0 in the very beginning?
If I modify it to, lets say 1, I get a different output. The code then prints all primes starting from 5 instead of 2. Why are the other numbers skipped?
Explanation
Have a close look at your loop logic flow:
for (int i = number1; i <= number2; i++) {
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
temp = 1;
break;
} else {
temp=0;
}
}
if (temp == 0) {
System.out.println(i);
}
}
i starts as 2 and increments. The inner loop is:
for (int j = 2; j <= i / 2; j++) {
Inner loop is skipped
That means that for the first iterations of the outer loop, for example i = 2 the condition of the inner loop evaluates to:
j <= i / 2
// which is
2 <= 2 / 2
// which is
2 <= 1
Hence the inner loop does not even enter at all and is skipped. So we directly reach
if (temp == 0) {
System.out.println(i);
}
The same is true for the iterations, i = 3.
i = 4 is the first iteration that actually enters the inner loop and starts overwriting temp with either 0 or 1.
Meaning of temp == 0
So during the first iterations of the outer loop (i = 2, i = 3), the initial state of temp plays a role, since it determines whether i will be printed or not.
So you need it to start as 0 to have the first values, for which the inner loop is not even entered, included in the output.
Notes
That said, using temp in such a way is overly complicated. It would be better if it would be moved to the place where it is actually needed, inside the loop, given a better name and also changed to a boolean. All in all, you may simplify the code as follows:
int min = 2;
int max = 100;
System.out.println("prime numbers between" + min + "and" + max + "are :");
for (int i = min; i <= max; i++) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(i);
}
}
And if you are willing to introduce a helper method like:
public static boolean isPrime(int candidate) {
for (int i = 2; i <= candidate / 2; i++) {
if (candidate % i == 0) {
return false;
}
}
return true;
}
Your code will heavily simplify and be very easy to read:
int min = 2;
int max = 100;
System.out.println("prime numbers between" + min + "and" + max + "are :");
for (int i = min; i <= max; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
you need to understand, what is the role of the variable temp in this code.
The variable temp is behaving like a flag, means whenever the number found to be divisible by another number, temp variable is setting as 1 and the code stops checking.
if we scan all the number upto i/2 and the variable temp is still 0, means we didn't find any number j which can divide current number i, then the current number is prime.
edit:
the role of temp=0 at the very beginning assumes all the number is prime. if found later number is divisible then we are assigning temp=1 and we get to know that the number is not prime.
The role in temp is to simply indicate if a prime was or was not found. Then use that value to control printing of the value under test. But it is not really needed (and as already stated in the comments, should have been a boolean).
Here is one way you could improve your effort without using that value.
Other than dividing by already found primes, you can make it somewhat more efficient by doing the following:
If the first prime is even, check to make certain it isn't 2.
if it is, print it.
if even, increment number1 by 1 to make it odd.
then starting iterating by both candidates and divisors by two to get just the odd numbers.
don't divide by any number > the square root of the candidate. Otherwise you are wasting time. Example, if 97 is not divisible by any of 3,5,7,11 then it must be a prime because any larger divisor would return a quotient < 11 which has already been checked.
you don't need a temp value. Just continue to the outer loop if the number is divided. Otherwise, print the number.
int number1 = 2, number2 = 100;
System.out.println("prime numbers between" + number1 + "and"
+ number2 + "are :");
if (number1 % 2 == 0) {
if (number1 == 2) {
System.out.println(2);
}
number1++;
}
outer:
for (int i = number1; i <= number2; i += 2) {
int max = (int)Math.sqrt(i);
for (int j = 3; j <= max; j += 2) {
if (i % j == 0) {
// try next candidate
continue outer;
}
}
// must be a prime so print it.
System.out.println(i);
}
A better approach is to use the Sieve of Erastosthenes. A BitSet is perfect for this. The idea is to:
mark every bit that is not a prime.
This eliminates composite numbers since it eliminates all their prime factors from the composite positions in the bitset.
The unset bit positions in the bitset are then primes.
as the list is being built, the first unset (clear) bit in the list is as prime.
BitSet bits = new BitSet();
bits.set(0,2); // set bits 0 and 1
initialize nextBit to the first prime
int nextBit = 2; // essentially bitSet.nextClearBit(0);
Continue the loop while the next bit is less than the square root of the terminal value.
while (nextBit <= Math.sqrt(number2)) {
// mark every prime position after this one.
for (int i = 2*nextBit; i < number2; i += nextBit) {
bits.set(i);
}
// the next clear bit after the previous prime must be a prime
// since it is next unset bit
nextBit = bits.nextClearBit(nextBit+1);
}
Now display them
// This is done by simply printing all the bit positions
// that are clear up to the terminal value.
int i = bits.nextClearBit(0);
while (i < number2) {
System.out.println(i);
i = bits.nextClearBit(i+1);
}

counting negative numbers in array

I am trying to find the counts for negative numbers in a 2d-array ( square- matix). In matrix if you go from up to down and left to write number increases. Logic here is to start from last column and proceed to the left. If you find the neg num then increase the row index and proceed the same way till the last row. I am getting the error in java code but not in python.
public class O_n
{
public static void main(String[] args)
{
int firstarray[][] = {{-2,-1,0},{-1,0,1},{0,1,2}};
int secondarray[][] = {{-4,-3,-2},{-3,-2,-1},{-2,-1,0}};
System.out.print ("First array has"+count_neg(firstarray));
System.out.println("negative numbers");
System.out.print ("Second array has"+count_neg(secondarray));
System.out.println("negative numbers");
}
public static int count_neg(int x[][]){
int count = 0;
int i = 0; //rows
int j = x.length - 1; //columns
System.out.println("max column index is: "+j);
while ( i >=0 && j<x.length){
if (x[i][j] < 0){ // negative number
count += (j + 1);// since j is an index...so j + 1
i += 1;
}
else { // positive number
j -= 1;
}
}
return (count);
}
}
I am getting this output
max column index is: 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at O_n.count_neg(O_n.java:22)
at O_n.main(O_n.java:9)
/home/eos/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java
returned: 1
BUILD FAILED (total time: 0 seconds)
What is wrong with this code? the same thing worked in python...
def count_neg(array):
count = 0
i = 0 # row
j = len(array) -1 # col
# since we are starting from right side
while j >= 0 and i < len(array):
if array[i][j] < 0:
count += (j + 1)
i += 1
else:
j -= 1
return count
print(count_neg([[-4,-3,-1,1],[-2,-2,1,2],[-1,1,2,3],[1,2,4,5]]))
I would write the method like this, just go through the 2d array and increase count each time a negative number is found
public static int count_neg(int x[][]){
int count = 0;
for(int i = 0; i < x.length; i++){
for(int j = 0; j < x[i].length; j++){
if(x[i][j] < 0){
count++;
}
}
}
return (count);
}
Your indexes are reversed from the python version:
while j >= 0 and i < len(array)
To the Java version:
while (i >= 0 && j < x.length)
// Change to
while (j >= 0 && i < x.length)
Output:
max column index is: 2
3
If you are using Java8, you can use streams to implement count_neg:
public static int countNeg(int x[][]) {
long count = Stream.of(x)
.flatMapToInt(arr -> IntStream.of(arr))
.filter(i -> i < 0)
.count();
return Math.toIntExact(count);
}
First of all your algorithm don't find the count of negative numbers.
Here are the results of the python code:
print(count_neg([[1, 1, -1],[1, 1, -1],[1, 1, -1]])) result - 9
print(count_neg([[1, 1, -1],[1, 1, 1],[1, 1, 1]])) result - 3
So the provided code finds sum of column indexes + 1 for some negative numbers, not all. And for your test arrays it's return pseudo correct counts.
To find the count of negative numbers in a two-dimentional array you just have to get each number, check if the one is less than zero and increase the counter by one if it's true. So it's impossible to get the correct result with complexity better than O(n2).
Here the correct code in Java of doing that:
public static int count_neg(int x[][]){
int count = 0;
for(int i = 0; i < x.length; i++){
for(int j = 0; j < x[i].length; j++){
if(x[i][j] < 0) count++;
}
}
return count;
}
Here a small change in the algorithms to produce correct result with columns which don't contain negative numbers:
while j >= 0 and i < len(array):
if array[i][j] < 0:
count += (j + 1)
i += 1
else:
j -= 1
if j < 0:
i += 1
j = len(array) - 1
You can test it with the following array [[1,2,4,5],[-2,-2,1,2],[-1,1,2,3],[1,2,4,5]]

Java Program to print all odd integers up to N and print 10 integer per line

I'm having a little trouble with my program. I already wrote my user validation and I can print all odd numbers up to what the user inputed. My problem is trying to get 10 integers on every line. Obviously, I tried the i % 10 == 0 technique and as you know odd number can't have a remainder of zero. If you could give some tips or guidance that's be fantastic!
import java.util.*;
public class Question {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
System.out.print("Please enter a number. ");
n = input.nextInt();
while(n < 0 || n > 1000){
System.out.print("Error: 0 <= N <= 1000. Reenter.");
n = input.nextInt();
}
for(int i = 1; i <= n; i+=1) {
System.out.print(" " + i);
if(i % 10 == 0)
System.out.print("\n");
}
}
}
The following logic seems to work:
for (int i=1; i <= n; i+=1) {
if (i % 2 == 1)
System.out.print(" " + i);
if (i % 20 == 0)
System.out.print("\n");
}
The basic idea here is that the (i % 2 == 1) condition prints only odd numbers, and the (i % 20 == 0) adds a line break every ten numbers. The reason we use mod 20 is that there are ten odd numbers for every 20 counting numbers.
Demo
Here's what I came up with
int count = 0;
for(int i = 1; i <= n; i+=1) {
if (i % 2 == 1){
System.out.print(" " + i);
count += 1;
continue;}
if(count % 10 == 0)
System.out.print("\n");
}
Adding a count which only increases when an odd number is printed means that you can test to see if it is divisible by 10.

Java do while loop increment

int i = 10;
int j = 0;
do {
j++;
System.out.println("loop:" + j);
while (i++ < 15) { //line6
i = i + 20;
System.out.println(i);
} ;
} while (i < 2);
System.out.println("i_final:" + i);
Output:
loop:1
31
i_final:32
Why the i_final is 32 and not 31? As we can see the do_while loop has executed only once, so line 8 should also have executed only once, hence incrementing the value of "i" by 1. When did 31 increment to 32?
While loop will be executed twice before its break.
while (i++ < 15) { //line6
i = i + 20;
System.out.println(i);
} ;
First it increment to 11 .
Check with 15. Returns true.
Now it increments to 31. (i = i + 20)
now again while loop .
it increments the value .
when you are doing a while loop as (i++ < 15) , it checks the condition and stop the loop if i++ is < 15 , But here when you do a do while loop j++ the loop goes 2 times and when it comes to while (i++ < 15) it increaments the value of i by 1 and stops... so in second loop the value of i increases by one but the function inside the while loop remains the same as it stops when i++ is > than 15
IF you do the following you will get 31
int i = 10;
int j = 0;
do {
j++;
System.out.println("loop:" + j);
while (i < 15) { //line6
i++
i = i + 20;
System.out.println(i);
} ;
} while (i < 2);
System.out.println("i_final:" + i);
First time when while loop condition is checked i=11, after that i is incremented by 20, so i=31. Then while condition is checked again, when found that 31 < 15 is false i is still incremented by 1. So i =32

loops and probabtily

i have to Have the computer compute all the possible ways three dice can be thrown: 1 + 1 + 1, 1 + 1 + 2, 1 + 1 + 3, etc. Add up each of these possibilities and see how many give nine as the result and how many give ten.
public class prog209b
{
public static void main(String []args){
int sum = 0;
int count = 0;
do{
for(int i = 1; i<=6; i++){
count +=1;
for(int y=1; y<=6; y++){
count += 1;
for(int x=1; x<=6; x++ ){
sum = i + y + x;
}
}
}
}while (sum == 10 && count == 27);{
System.out.println("There are " +count +" ways to get ten");
}
}
}
Thats what i came up with but i can get it to work correctly at all. instead of giving me that theres 27 ways it gives me like 42. Obviously im not doing this correctly. Please help me before i have an aneurysm
I'm not going to do your homework for you but:
You don't need the do/while loop - why would you need to keep going once you'd found all the possibilities?
You don't need to count all the possible dice rolls - you need to count how many give 9 as a total, and how many give 10. You could either do that with two variables, or you could make a method which took the "target" as a parameter
You don't need the sum other than right in the innermost loop - all you need to do is find out whether the sum of the values is equal to one of your target values, and increment the appropriate counter...
Your count += 1s are in the wrong place and your while (sum == 10 && count == 27) makes no sense.
int nine = 0
int ten = 0;
for(int i = 1; i<=6; i++){
for(int y=1; y<=6; y++){
for(int x=1; x<=6; x++ ){
sum = i + y + x;
if (sum == 9) nine++;
if (sum == 10) ten++;
}
}
}
You should do something like this:
for(int i = 1; i<=6; i++){
for(int y=1; y<=6; y++){
for(int x=1; x<=6; x++ ){
sum = i + y + x;
if (sum == 10)
count++;
}
}
}
System.out.println("There are " + count + " ways to make 10");

Categories

Resources