i set an if to check if the numbers being sent we're divisible by 3 or 7 or so on..
but it doesn't seem to do that.
i tried changing how it worked which is why it looks like this now but it still doesn't work.
public void primeNumbers() {
System.out.println("Enter the amount of prime numbers you'd like: ");
int numberOfPrimes = reader.nextInt();
int numbersFound = 0;
int foundCount = 0;
while(foundCount < numberOfPrimes) {
if (numbersFound < 2) {
numbersFound++;
}
else if(numbersFound % 3 == 0 || numbersFound % 5 == 0 || numbersFound % 7 == 0 || numbersFound % 11 == 0 || numbersFound == 2) {
System.out.print(numbersFound +" ");
foundCount++;
numbersFound++;
}
else {
numbersFound++;
}
}
}
no errors, it's just the numbers coming out aren't prime.
I figured out why it wasn't working.
I just forgot to set a condition that said that if the number is divisible by 2, then skip.
And instead of making all the numbers that are divisible by 3 7 5 and 11 be printed
i make them not be printed
im pretty sure
Sorry lol
Related
I have a question regarding an answer that was given here a while ago.
I came up with the same answer myself in the code attached but I'm trying to understand why do I need to divide the input number by 2 (line 10), and not just let the loop run its course till the value of the input number achieved.
1 import java.util.Scanner;
2 public class numIsPrime {
3 public static void main(String[] args) {
4 Scanner sc = new Scanner(System.in);
5 int i = 2;
6 boolean isPrime = true;
7 System.out.println("Enter a number");
8 int num = sc.nextInt();
9
10 while (i < num ) // (i <= num / 2)
11 {
12 if (num % i == 0)
13 isPrime = false;
14 i++;
15 }
16
17 if (isPrime)
18 System.out.println(num + " is a prime number");
19 else // !isPrime
20 System.out.println(num + " isn't a prime number");
21
22 }
23 }
This is the simplest way to calculate if an integer n is probably a prime:
public static boolean isPrime (int n) {
if (n < 2) return false;
BigInteger bigInt = BigInteger.valueOf(n);
return bigInt.isProbablePrime(100);
}
You can insert this function call in a loop where you can pass a new number every iteration. I am using the implementation of BigInteger provided by Java to do the calculation, rather than writing my own. UNLESS this is a homework and you are required to write your own algorithm, I would use this solution.
This base method can then be used for calculating other types of prime numbers. A complete answer can be found here.
UPDATE:
The int parameter in BigInteger.isProbablePrime(int) is a measure of the uncertainty that the caller is willing to tolerate. The larger the number, the "slower" it executes (but the more certain it is). Also, going back to the original question (already answered in the OP's comments section):
why do I need to divide the input number by 2 (line 10), and not just
let the loop run its course till the value of the input number
achieved.
This is an optimization that will make your evaluation run twice as fast. For example, suppose an evaluation of n integers take 10 minutes to complete, excluding even numbers should take half the time. That's a significant improvement. Although you should not optimize prematurely, these sort of optimizations should be done right from the get go. Basically, we all know that even numbers are not prime, so why evaluate it? You want to evaluate unknowns. In my solution, I only evaluate values greater than 2 because by definition, values less or equal to 2 are not prime. I am merely solving that by definition or by mathematical properties.
As mentioned in the comments, dividing by 2 is a simplest optimization to reduce the number of checks, however, existing code has a few issues (e.g. returning true for 0 and 1 which are NOT prime numbers) and may be further optimized:
break/end the loop as soon as isPrime is set to false
skip even numbers by incrementing by 2
calculate until i * i <= num
If this limit is reached, it means that no factor i of num has been found in the range [2, num/i], therefore by definition of the prime numbers, all the remaining numbers in the range [num/i, num] are neither the factors of num, and therefore num is prime.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int num = sc.nextInt();
boolean isPrime = num > 1 && (num % 2 != 0 || num == 2);
int i = 3;
while (isPrime && i * i <= num) {
if (num % i == 0)
isPrime = false;
i += 2; // skip even numbers
}
if (isPrime)
System.out.println(num + " is a prime number");
else
System.out.println(num + " isn't a prime number");
More optimizations are possible if the divisibles of 3 (except 3) are excluded similar to the exclusion of even numbers, then the search continues from 5 and the candidates for primality comply with 6n ± 1 rule (e.g., 5 = 6 - 1, 7 = 6 + 1, 11 = 12 - 1, 13 = 12 + 1, etc.):
boolean isPrime = num > 1 && (num % 2 != 0 || num == 2) && (num % 3 != 0 || num == 3);
int i = 5;
int d = 2;
while (isPrime && i * i <= num) {
if (num % i == 0)
isPrime = false;
i += d; // check only non-even numbers
d = 6 - d; // switch 2 to 4 and back to 2
}
Everybody knows that FizzBuzz question that interviewers ask students.
Basically, when you have an incrementor and for each number which is a divisible of 3 you say fizz, for a number divisible by 5 you say buzz, while if it is divisible by both(3 and 5) you say FizzBuzz, hence the name.
It is a relatively easy problem to solve and I have done it, but I think my solution is a bit clunky. This is it:
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i;
}
for (int i : numbers) {
if (i % 3 == 0) {
System.out.println("Fizz");
} else if(i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println("FizzBuzz");
}
}
But the problem is that when the number is divisible by both 3 and 5 it gives me "Fizz" for some reason. Can somebody explain to me, because I'm new to java programming. Thanks in advance!
The problem lies in the order of your if statements. Lets take a look at the number 15, which is the first number divisible by both 3 and 5. Because of the order in which you have your if statements, the first statement that is checked is
if ( 15 % 3 == 0)
The result of the operation is indeed equal to 0, as 15 is divisible by 3 and so "Fizz" is printed and your else is ignored.
Think about how you should structure the order of your if statements and which additional condition should you introduce to catch the specific case of being divisible by both i % 3 == 0 && i % 5 == 0.
When you enter the if statement and your number is 15 for exemple, you enter the first if statement and.. prints "Fizz" as you stated, because 15 % 3 == 0 returns true. Then it ignores the else.
You want the first if to be
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");*
}
Try this code
public static void main(String[] args) {
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i;
}
for (int i : numbers) {
if ((i % 3 == 0) && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if(i % 5 == 0) {
System.out.println("Buzz");
} else if (i % 3 == 0){
System.out.println("Fizz");
}
}
}
I'm doing a hackernet challenge where n is an int input. The conditions are:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird.
Im sure the code makes logic and dont think theres syntax. It gives the correct responses and hackernet still says its incorrect so ive come here to see if anyone can see what the problem is
public static void main(String[] args)
{
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20)
{
System.out.print("weird");
}
else
{
System.out.print("not weird");
}
}
The problem is the logic in your else condition, which would also catch values of N which are less than 2. Try this version:
if (N % 2 != 0)
{
System.out.print("weird");
}
else if (N >= 2 && N <= 5 || N > 20)
{
System.out.print("not weird");
}
else if (N >= 6 && N <= 20)
{
System.out.print("weird");
}
else
{
// NOTE: if the code still fails, remove this else condition
System.out.print("unexpected value of N");
}
Note: To get your code to pass the Hackernet task, you might have to completely remove the else condition. I added it for completeness, but Hackernet might test N=1 to see if nothing gets printed.
Read this condition :
if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20)
as
if (N % 2 != 0 || (N % 2 == 0 && N >= 6 && N <= 20))
Then see how operator precedence changes the behaviour and yield desired results.
Check the following one
public static void main(String[] args)
{
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if(N%2!=0) {
System.out.print("weird");
}else if(N>=2 && N<=5) {
System.out.print("not weird");
}else if(N>=6 && N<=20) {
System.out.print("weird");
}else if(N>20) {
System.out.print("not weird");
}
}
For the technical part: start by reading about
precedence of java operators and then make your code easier to read.
Pushing that many conditions into a single if is not helpful. You see it yourself: you think the code is correct, but probably it isn't. And now you look to other people to explain your overly complex code back to you. And of course, all the other answers do all that for you ... but beyond that:
The "real" answer here is: learn how to test your code.
Instead of having a main that somehow asks for a number, and then makes decisions, write a method boolean isWeird() that takes a number and returns true/false according to your requirements.
And then simply test that method with all reasonable cases. And then check if that result is as expected.
Using JUnit, you could write something like
assertThat(isWeird(1), true);
assertThat(isWeird(21), true);
assertThat(isWeird(22), true);
...
Ideally, you write such tests before you implement that method. And then you implement all the conditions, and any check that fails tells you that you got something wrong.
I feel, In the if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20) condition, you are verifiying the odd and even values at same time using && and || operator. Can you modify the condition into like this if (N % 2 != 0 || (N % 2 == 0 && N >= 6 && N <= 20)) and check? If N is odd weird will be printed or if N is even and it falls under the 6 and 20 inclusive, weird will be printed.
You already have a good few answers here but if you think logically about what you actually need, you can break it down easier.
It looks like the only "Not Weird" print out is 2, 4 and even numbers > 20
So an example could be something like:
if (n % 2 == 0) {
if ((n >= 2 && n <= 5) || (n > 20)) {
return "Not Weird";
}
}
return "Weird";
You can try this
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if (n % 2 == 1 || (n >= 6 && n <= 20)) {
System.out.println("Weird");
} else {
System.out.println("Not Weird");
}
scanner.close();
}
So, I want to find what numbers between 1 and 100 are divisible by 3 and 7. I got it to work, except for one of the numbers. For some reason, 3 % 3 is giving me 3 as a remainder, but 6 % 3 is giving me 0. This is my code:
public class factors
{
public static void main(System args[])
{
//Variables
int integer, remainder;
//Displays header
System.out.print("Integers less than 100 that are \nevenly divisible by 3 or 7");
//Loops through each integer
for (integer = 1; integer <= 100; integer++)
{
remainder = integer % 3; //determines if 3 is a factor
if (remainder == 0) //displays integer
{
System.out.println(integer + " is divisible by 3");
}
remainder = integer % 7; //determines if 7 is a factor
if (remainder == 0) //displays integer
{
System.out.println(integer + " is divisible by 7");
}
}
}
}Does anyone know why this isn't working for the number 3?
You code is actually doing
remainder = 3 % 7; // equals 3.
The best way to determine why your code is not doing what you think is to step through your code using a debugger.
All the multiples of 3 & 7 will be multiples of 21, i.e. 21, 42, 63, 84.
Your 3 is getting tacked onto the end of the line of text above. You'll be seeing
Integers less than 100 that are
evenly divisible by 3 or 73
because you wrote print instead of println for this line of text. The % operator is working just fine, and 3 % 3 is indeed 0, not 3.
You are not outputting a remainder - you are displaying integer. So for 3 it should print 3.
Make you print statements more definite:
System.out.println(integer + " is divisible by 3"); // for the first `if`
and
System.out.println(integer + " is divisible by 7"); // for the second `if`
This should clear your confusion.
Your logic prints number divisible by 3 or 7.
Firstly, your code can be shortened to:
//and
for (int i = 1; i <= 100; i++){
if(i % 3 == 0 && i % 7 == 0) {
System.out.println(i);
}
}
//or
for (int i = 1; i <= 100; i++){
if(i % 3 == 0 || i % 7 == 0) {
System.out.println(i);
}
}
Also I note you're not declaring a type for your integer, remainder variables. I didn't attempt to recreate with those issues; start by solving that.
I got a question about this program, it says: The FizzBuzz Challenge: Display numbers from 1 to x, replacing the word 'fizz' for multiples of 3, 'buzz' for multiples of 5 and 'fizzbuzz' for multiples of both 3 and 5. Th result must be:1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 ...
So my problem is at the time to print the output, I dont know what to do.
public class Multiplos {
public static void main(String args[]) {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) {
System.out.print(i + " ");
System.out.print(" fizz ");
}
if (i % 5 == 0) {
System.out.print(" " + i);
System.out.print(" " + "buzz ");
}
if((i % 3 == 0)&&(i % 5 == 0)){
System.out.print(i + " ");
System.out.print(" fizzbuzz ");
}
}
}
}
Here's the pseudocode:
for i in 1 to 100
if(i % 5 == 0) AND (i % 3 == 0) print 'fizzbuzz'
else if(i % 3 == 0) print 'fizz'
else if(i % 5 == 0) print 'buzz'
else print i
I'll leave it as an exercise for you to convert it into Java, as that might help with the understanding as to how this works.
The problem is of course that when (i % 3 == 0)&&(i % 5 == 0) is true, the two preceding conditions are also true, so you get duplicated output. The easiest way to fix that is to check that the other condition is not true in the first two cases. I.e. make the first condition if((i % 3 == 0)&&(i % 5 != 0)) and the same for the second.
The other problem with your code is that you're printing the number when any of the cases is true, but you're supposed to print it when none of them are. You can fix that by making a fourth if-condition which checks that none of the conditions are true and if so, prints i.
Now if you did the above, you'll see that you ended up with some code duplication. If you think about it a bit, you'll see that you can easily fix that, by using if - else if - else if - else, which allows you to assume that the previous conditions were false when the current condition is checked.
Hm, I think I'll only hint:
Think of the correct order: What happens if a number is a multiple of 3, but also of (3 and 5)?
There is an else if statement.
Use else if so that the conditional don't overlap.