Duplicating prime numbers of even numbers - java

This part of an assignment requires to check every even number in an array for 2 prime numbers that add up to that even number. I already managed to find all the primes between 2 and each even number and put those primes in a separate array list. I've already found how to find 2 prime numbers that add up to each even number; however when I check the output, it gives me multiple answers like this:
How many numbers would you like to compute:
12
Your two prime factors that add up to 4 are:
2 & 2
Your two prime factors that add up to 6 are:
3 & 3
Your two prime factors that add up to 8 are:
3 & 5
Your two prime factors that add up to 8 are:
5 & 3
Your two prime factors that add up to 10 are:
3 & 7
Your two prime factors that add up to 10 are:
5 & 5
Your two prime factors that add up to 12 are:
5 & 7
Your two prime factors that add up to 12 are:
7 & 5
All I want is ONE pair of primes that sum up to each even number in a loop. My code looks like this:
//For Loop looks at every even number in the arrayList
//for(int c = 0; c < len; c++) {
//Code for Numbers that come before every even number
//Code for Finding primes
//Finding prime numbers that add up to even number
int len3 = primeNumbers.size();
for(int f = 0; f < len3; f++) {
if(primeNumbers.get(f) + primeNumbers.get(f) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(f));
break;
}
for(int g = 1; g < len3; g++) {
if(primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
break;
}
}
}
}

Try this. Your second loop should start from f. So if you do that u can remove the first if you have and then have this. I havent tested it. But try and let me know if it works.
for(int f = 0; f < len3; f++) {
for(int g = f; g < len3; g++) {
if(primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
}
}
}

When you call break statement it simply break current loop if your method only handle this logic simply change break statement to return. Hope this is you expect :
int len3 = primeNumbers.size();
for (int f = 0; f < len3; f++) {
if (primeNumbers.get(f) + primeNumbers.get(f) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(f));
return;
}
for (int g = 1; g < len3; g++) {
if (primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
return;
}
}
}

Related

The total number of digits between two numbers

I am working on a program right now and part of it requires me to find the total amount of digits between two integers, I have figured it out for integers that have the same amount of digits, e.g. 1234 and 4980 (both have four digits) but I can't seem to figure it out for the integers that don't have the same amount of digits, i.e. 3 and 5698 (3 only has one digit and 5698 has four). How might I go about this?
Boy, the algorithm is not obvious – your last comment is rather crucial.
Evidently this question boils down to:
For each 'number' between the 2, including both of the edges, count how many digits that number has.
Sum those up.
For your example it's simply (4980 - 1234 + 1) * 4 = 14988.
Sounds like you simply need to for-loop: for (int i = 1234; i <= 4980; i++), and then for each i just figure out how many digits there are and add those.
An straightforward way is to use logarithms. The number of digits in an integer n is (int)Math.log10(n)+1. Assuming you are doing inclusive computations on first thru last it would be as follows:
int sum = 0;
int first = 3;
int last = 3333;
for (int i = first; i <= last; i++) {
sum += Math.log10(i)+1;
}
System.out.println(sum);
prints
12223
But a more efficient and perhaps less obvious way it to forgo logs and simply compute in pieces. This will reduce number of iterations of the loop. This works by computing the number of digits and the power in increments. I put in print statements so you can see the progression.
int digits = 1;
int power = 10;
int limit = last;
sum = 0;
while(power < limit) {
if (power > first) {
sum += (power - first) * digits;
System.out.println(power + " " + first + " " + digits + " : partial running sum = " + sum);
first = power;
}
digits++;
power*= 10;
}
sum += (limit - power/10 + 1)*digits;
System.out.println(limit + " " + power/10 + " " + digits + " : partial running sum = " + sum);
System.out.println(sum);
prints
10 3 1 : partial running sum = 7
100 10 2 : partial running sum = 187
1000 100 3 : partial running sum = 2887
3333 1000 4 : final sum = 12223
12223

Write a program using 1-D arrays with values from a random generator to print out how many times each combination was rolled by a pair of dice

The goal of the assignment is to use parallel 1-D arrays, but 2-D arrays are also allowed.
I can print out the different combinations such as 1,1 (otherwise known as snake eyes) rolled by the pair of dice.
Trying to print out the number of times each combination was rolled without printing the combination the same number of times it was rolled is difficult.
Ex:
Enter the number of times you want to roll a pair of dice:
5
You rolled: 1 and 5 a total of 1 times - What I don't want
You rolled: 4 and 3 a total of 1 times
You rolled: 1 and 5 a total of 2 times - For duplicates this is all I want to print
You rolled: 3 and 3 a total of 1 times
You rolled: 2 and 2 a total of 1 times
I know the loop for printing it out right after it increments the combo array (which holds the number of times each combination was rolled) is not correct, but I am stuck on how to modify it.
I consider combo[0][0] to be the number of times 1,1 is rolled, combo[0][1] to be the number of times 1,2 is rolled, and so on.
import java.util.Scanner;
public class Dice {
Scanner read = new Scanner(System.in);
Random diceRoll = new Random();
int numRolls;
int[] dice1 = new int [1000];
int[] dice2 = new int [1000];
int[][] combo = new int[6][6];
public void getRolls()
{
System.out.println("Enter the number of times you want to roll a pair of dice: ");
numRolls = read.nextInt();
dice1 = new int[numRolls];
dice2 = new int[numRolls];
for (int i = 0; i < dice1.length; i++)
{
dice1[i] = diceRoll.nextInt(6) + 1;
dice2[i] = diceRoll.nextInt(6) + 1;
}
System.out.println("\n");
for (int j = 0; j < combo.length; j++)
{
for (int k = 0; k < combo[0].length; k++)
{
combo[j][k] = 0;
}
}
for (int m = 0; m < numRolls; m++)
{
combo[dice1[m] - 1][dice2[m] - 1]++;
System.out.println("You rolled: " + dice1[m] + " and " +
dice2[m] + " a total of " + combo[dice1[m] - 1][dice2[m] - 1] +
" times");
}
You should separate the combo calculation loop from the printing loop. If the order is not relevant as you stated, that should give you the correct output you’re looking for. Happy coding!
Self-answer:
I made the printing loop separate from the combo calculation loop.
If the combo value for the combination is 1, then I simply print it out stating it was rolled 1 time.
If the combo value for the combination was greater than 1, I print it out at the first occurrence stating it was rolled that many times, then set the combo value for that combination equal to 0. Only combos with at least a combo value of 1 are printed, so duplicate lines cannot be printed (i.e. 1,1 rolled 4 times only prints on one line now instead of 4 separate lines).
for (int m = 0; m < numRolls; m++)
{
combo[dice1[m] - 1][dice2[m] - 1]++;
}
for (int m = 0; m < numRolls; m++)
{
if (combo[dice1[m] - 1][dice2[m] - 1] > 1)
{
System.out.println("You rolled: " + dice1[m] + " and " + dice2[m] + " a total of " + combo[dice1[m] - 1][dice2[m] - 1] + " time(s)");
combo[dice1[m] - 1][dice2[m] - 1] = 0;
}
if (combo[dice1[m] - 1][dice2[m] - 1] == 1)
{
System.out.println("You rolled: " + dice1[m] + " and " + dice2[m] + " a total of " + combo[dice1[m] - 1][dice2[m] - 1] + " time(s)");
}
}

Alternate between operations in a for-loop

I'm a Java beginner, please bear with me. :) I haven't learned anything like if statements and such yet, I've only learned about loops, variables, and classes. I need to write a single loop which produces the following output:
10 0 9 1 8 2 7 3 6 4 5 5
I can see from the segment, that the difference between the numbers is reduced by one, so from 10 to 0 it is subtracted 10, then from 0 to 9 it is added by 9, and it goes on alternating between adding and subtracting.
My idea was to create the loop where my variable i = 10 decreases by 1 in the loop (i--) but I'm not quite sure how to alternate between adding and subtracting in the loop?
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 0; i--) {
System.out.print(i + " ");
}
}
}
Why not have two extra variables and the increment one and decremented the other:
int y = 0;
int z = 10;
for(int i = 10; i >= 5; i--) {
System.out.print(z + " " + y + " ");
y++;
z--;
}
Output:
10 0 9 1 8 2 7 3 6 4 5 5
However we can also do this without extra variables:
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + 10-i + " ");
}
I don't think the OP actually wanted somebody to do their homework for them, so I'm gonna stick to answering the question they actually asked: how to alternate between two operations within a loop (so they can keep the algorithm they came up with :)).
There's a nifty "trick" that's very often used when we want to do something every other iteration in most programming languages. You'll most definitely come across it in your life, and it could be perplexing if you've got no clue what's going on, so here it goes!
The modulo (%) operator will yield the remainder of the division between its operands.
For instance, consider the following: 7 ÷ 2 = 3.5
When working for integers, you'd say that 7 ÷ 2 = 3, then you're left with 1.
In this case, when all variables are ints, in Java, 7 / 2 would be 3 and 7 % 2 is 1.
That's modulo for you!
What's interesting about this operator is inherent to what's interesting about division in general, and one case in particular: the remainder of a division by 2 is always either 0 or 1... and it alternates! That's the key word here.
Here comes the "trick" (not really a trick, it's basically a pattern considering how widely used it is) to alternating operations over iterations:
take any variable that is incremented every iteration in a loop
test for the remainder of the division of that variable by 2
if it's 0, do something, otherwise (it'll be 1), take the alternate path!
In your case, to answer your actual question (although others do have good points, I"m not trying to take that away from anybody), you could consider using something like that:
if( i % 2 == 0 ) {
// i is even, subtract
} else {
// i is odd, add
}
That'd allow you to keep going with the algorithm you initially thought of!
public class exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + (10-i) + " ");
}
}
}
Or you can do it this way, if you want to be a wiseass ;)
for(int i = 0, arr[] = {10,0,9,1,8,2,7,3,6,4,5,5}; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
This looks a bit like a homework assignment, so I won't give you working code.
But remember that you can put multiple print statements inside the for loop. You don't necessarily have to iterate 10 times to get your output. 5 times is totally enough. And as already stated in a comment above: the numbers alternate between i and 10-i, for the right range of i.
replace i >= 0 with i >= 5
add this : System.out.print((10-i--) + " ");
starting from what you did
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; ) {
System.out.print(i + " " + (10-i--) + " ");
}
}
}
Somethings don't need overthinking:
public class Answer2 {
public static void main(String[] args) {
for (int i = 0; i <= 5; i++){
System.out.println(i);
System.out.println(10 - i);
}
}
}
edit
You CAN and should generalize your task. Here is an example how you could do it (I won't write the method, since it's your job - instead I'll alter my answer just to show you the possibilities)
public class Answer2 {
private static final Random RANDOM = new Random();
public static void main(String[] args) {
//You can use any upper bound for 'someLength'
int someLength = 1 + RANDOM.nextInt(20);
for (int i = 0; i <= someLength / 2; i++) {
System.out.println(someLength - i);
System.out.println(i);
}
}
}
Who said that you can only use one System.out.print in the loop?
for (int i=0; i < 5; i++) {
System.out.print((10 - i) + " " + (i + 1) + " ");
}
You should think about generalizing the series. As you have observed, the series alternates between addition and subtraction. Also, the difference goes down by one at each step. You can define variables for these two and adjust them in the loop.
public static void main(String[] args) {
int term = 10;
int sign = 1;
for(int delta = 10; delta >= -1; delta--) {
System.out.print(term + " ");
sign = -1 * sign;
term = term + sign * delta;
}
}
Simply run a loop either starting from 0 or starting from 10.
1.
If you start from 10
for(int i=10;i>=5;i--){
System.out.print(i + " " + (10-i) + " ");
}
2.
If you start from 0
for(int i=0;i<=5;i++){
System.out.print((10-i) + " " + i + " ");
}
The output will be:
10 0 9 1 8 2 7 3 6 4 5 5
I tried this code. It worked for me.
for(int i = 10; i >= 5; i--) {
System.out.print(i + " ");
System.out.print(10-i + " ");
}
This is here. The output list is a list of combinations to make 10;
10 0 9 1 8 2 7 3 6 4 5 5
10 + 0 = 10
9 + 1 = 10
8 + 2 = 10
7 + 3 = 10
6 + 4 = 10
5 + 5 = 10
int n = 10;
int half = n / 2;
if(n % 2 == 1){
half++;
}
for(int x = n; x >= half;x--){
int remainder = n % x;
if(remainder == 0){
remainder = n - x;
}
System.out.print(x);
System.out.print(" ");
System.out.println(remainder);
}

Write statements in Java reads two integers and displays even numbers between them

Write statements that can be used in a Java Program two integers and display the number of even integers that lie between them. For example, the number of even integers that lie between 12 and 5 are 4
So far below is what i have.... the program outputs all the numbers between the two integers, and not the actual number of even integers.
Can someone please help / tell me what i am doing wrong ?
import java.util.Scanner;
public class evenNumberPrinter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the smaller integer");
int numOne = keyboard.nextInt();
System.out.println("Enter the larger integer");
int numTwo = keyboard.nextInt();
for (int i = numOne; i <= numTwo; i++) {
System.out.println(i + " ");
}
}
}
to calculate count of even numbers you don't have to use for loop, here is the formula:
static long evenCount(long a, long b) {
return ((Math.abs(a - b) + 1) >>> 1) + ((~((a & 1) | (b & 1))) & 1);
}
some clarification:
zero (0) is even number
count of even numbers obviously depends on distance between two values, lets pull some data:
0-0 - 1 number, distance 0 (0)
0-1 - 1 number, distance 1
0-2 - 2 numbers, distance 2 (0, 2)
0-3 - 2 numbers, distance 3
0-4 - 3 numbers, distance 4 (0, 2, 4)
0-5 - 3 numbers, distance 5
0-6 - 4 numbers, distance 6 (0, 2, 4, 6)
1-1 - no even, distance 0
1-2 - 1 number, distance 1 (2)
so, count of even numbers is determined by (distance+1)/2 plus one if both numbers are even
so, if we take distance Math.abs(a-b) + 1 divide it by two (>>>1) and then add 1 if and only if both numbers are even (a&1)==0
Another solution is to use pure math:
round the smaller number to the next even number (e.g. 5 to 6)
round the bigger number to the previous even number (e.g. 13 to 12)
subtract from the bigger rounded the smaller, e.g. 12-6 = 6
since even numbers are every second, divide it by 2 plus add one to count the first number of the range as well, that is 3+1=4
That is:
public static void main(final String[] args) {
final int number1=1;
final int number2=6;
int min=Math.min(number1, number2);
int max=Math.max(number1, number2);
min=min+min%2; // round up
max=max-max%2; // round down
final int evens=(max-min)/2+1; // even range plus the first number
System.out.println(evens); // Look ma, no loops
}
Edited to include explanation
Your for loop is doing nothing more than printing each number between numOne and numTwo. What you want to do is check to see if i is even or odd which can be accomplished using the modulus operator if i modulus 2 equals zero, then that number is even, and you should increment a counter variable each time this is true.
Change your for loop to something like this:
int evenCounter = 0;
for (int i = numOne; i < numTwo; i++){
if (i % 2 == 0){
System.out.print(i + " ");
evenCounter++;
}
}
System.out.println("There are " + evenCounter + " even numbers between " +
numOne + " and " + numTwo);
A little more optimal solution (if you want to print the numbers). Testing for parity (odd vs even) can be done only once, before entering the loop. Afterwards, just stay on even numbers by incrementing by 2.
int n = numOne;
int evenCount = 0;
if ((n%2)==1) { n++; }
while (n <= numTwo) {
System.out.println(n);
n += 2;
evenCount ++;
}
System.out.println( "There are " + evenCount + " even numbers between " + numOne + " and " + numTwo );
However, if your goal is only to determine how many there are (not print them), this is not optimal. A mathematical solution will be much faster.
int n = 0; //this is your counter
for (int i = numOne; i < numTwo; i++) { //use < numTwo instead of <= numTwo
//so it doesn't count numTwo as an int between your range
if (i%2 == 0) {n++;} //checks to see if number is even
// if it is, it adds one to the counter and moves on
}
System.out.println("there are " +n+ "even numbers between " +numOne+ " and " +numTwo); //prints out how many even ints were counted.

Need help using random numbers and modulos

I'm trying to make a simple program that will display 20 random numbers between 1 and 100 and then print out which numbers are divisible by 3 and equivalent to 1%3 and 2%3. It seems to work just fine but I've noticed it only works with the very last number in the list. What am I missing to include all the numbers in the search for my math? Thank you in advance for any help I can get!
import java.util.Random;
public class Lab5 {
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
for(int i=0;i<=repeat;i++){
n = rnd.nextInt(100)+1;
System.out.print(n+", ");
}
System.out.println();
System.out.println("-------------------------------------");
if(n % 3 == 0){
System.out.println("Numbers divisible by three: "+n+(", "));
}else{
System.out.println("Numbers divisible by three: NONE");
}
System.out.println("-------------------------------------");
if(n == 1 % 3){
System.out.println("Numbers equivalent to one modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to one modulo three: NONE");
}
System.out.println("-------------------------------------");
if(n == 2 % 3){
System.out.println("Numbers equivalent to two modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to two modulo three: NONE");
}
}
}
It is only printing the last number because the check if the number is divisible, etc is not in your for loop at the top. Simply copy and paste all of the code below it into your for loop and it should work as you intended.
You also have an error here: if (n == 1 % 3), it is legal but will check if n is equal to the remainder of 1 / 3. I don't think that is what you wanted to achieve, so correct it like this: if (n % 3 == 1) as Ypnypn suggested.
Your n is declared outside of the loop body, so its value will persist. However, since you are overwriting n in each loop iteration, only the last value of n will persist and will be used by other parts of the program.
As Ypnypn has said, correct your use of modulo, and as Arbiter and deanosaur have suggested, move the rest of the program logic inside the for loop
The correct syntax for modulus is n % 3 == 2. The current code n == 2 % 3 means n == 0, since the order of operations in Java requires that modulus is evaluated before equality.
You are putting all the output statements (System.out.println()) outside your loop, so it only outputs the last value.
Move your output statements so they are inside your loop:
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
int[] numbers = new int[3]; // To hold how many numbers have modulo 0, 1 or 2
for(int i = 0; i <= repeat; i++) {
n = rnd.nextInt(100)+1;
System.out.print(n+", ");
if(n % 3 == 0)
System.out.println("The number " + n + " is divisible by 3");
else
System.out.println("" + n + " modulo 3 = " + n % 3);
numbers[n % 3]++;
}
System.out.println("Numbers divisible by 3: " + numbers[0]);
System.out.println("Numbers with modulo 3 = 1: " + numbers[1]);
System.out.println("Numbers with modulo 3 = 2: " + numbers[2]);
}
Well .. you did not calculate anything in the loop, so your print statements work the last value of n after you exited the loop. Try something like
package com.example.modulo;
import java.util.Random;
public class Modulo {
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
int[] nMod = new int[3];
nMod[0] = 0;
nMod[1] = 0;
nMod[2] = 0;
for (int i = 0; i <= repeat; i++) {
n = rnd.nextInt(100) + 1;
nMod[n%3] = nMod[n%3] + 1;
System.out.print(n + " (" + n%3 + "), ");
}
System.out.println();
System.out.println("-------------------------------------");
System.out.println("Numbers divisible by three: " + nMod[0] + (", "));
System.out.println("Numbers equivalent to one modulo three: " + nMod[1] + (", "));
System.out.println("Numbers equivalent to two modulo three: " + nMod[2] + (", "));
}
}

Categories

Resources