I am trying to do the Sieve of Eratosthenes using a for loop then an if statement by checking for prime numbers up to 30 however I have a problem. Because of my code 2,3 and 5 are all shown as not prime numbers because they are divisible by 2,3 and 5 of course. How do I edit my code to make these come up as prime numbers?
Here is my code
public class prime {
public static void main(String[] args) {
for(int a=2; a<=30; a++){
if(a%2 == 0 || a%3 == 0 || a%5 == 0){
System.out.println(a +" = Not Prime");
}
else
{
System.out.println(a + " = Prime");
}
}
}
}
Thanks
Add an if statement to explicitly test for a being 2,3 or 5 before you test for divisibility.
The definition of a prime is that it is not divisible by another natural number other than 1 or itself. So, you need to devise a test for this, e.g., a != 2, etc., or, a / 2 != 1. In your code:
if (a != 2 && a % 2 == 0 || ...
Thanks for the help, I added some code in in the if statement to check if its 2, 3 or 5.
public class prime {
public static void main(String[] args) {
for(int a=2; a<=30; a++){
if(**a != 2** && a%2 == 0 ||**a !=3** && a%3 == 0 ||**a != 5** && a%5 == 0){
System.out.println(a +" = Not Prime");
}
else
{
System.out.println(a + " = Prime");
}
}
}
}
Related
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 have a given number. How can I find the factors of that number (for example, 5 and 3 for the number 15)? Here is the code I tried:
int factor1 = 2;
while ((a % factor1 != 0) && (a >= factor1)) {
d++;
}
if (factor1 == a){
d = 1;
}
But this gives me only the smallest factor (i.e a=3 all the time). I would like to get a random set of factors.
Loop through each number from 1 to N inclusively using the modulus operator (%). If n%currentNumber==0, they are a factor. Below, I did this using a for loop, outputting each factor as it is found.
int number=15;
for(int i = 1; i <= number; i++){
if(number%i==0){
System.out.println("Found factor: " + i);
}
}
As Theo said in a comment on this post, you can also use number/2, and arbitrarily include 1 and number.
int number=2229348;
System.out.println("Found factor: " + 1);
for(int i = 2; i <= number/2; i++){
if(number%i==0){
System.out.println("Found factor: " + i);
}
}
System.out.println("Found factor: " + number);
You can iterate through the numbers from 2 to a/2 and check if the given number divides a, which is done using the % operator:
int a = 15;
System.out.print("Divisors of " + a + ": ");
for(int i = 2; i <= a/2; ++i) {
if(a % i == 0) {
System.out.print(i + " ");
}
}
System.out.println();
This code prints all of the divisors of a. Not that you most probably want to ignore 1, since it divides all integers. Moreover, you don't need to check the numbers until a, because no number bigger than a / 2 can actually divide a apart from a itself.
The while loop with default values of a=15 and multiple=2 is already in an infinite loop. You need to correct that and check for subsequent increments of multiple whenever a%multiple ! = 0
public class Factors {
public static void main(String[] args){
/**
int multiple1=2,d=0,a=15; //multiple to be rephrased as factor
while((a%multiple1 != 0)&&(a>=multiple1)){
multiple1++; //this will increment the factor and check till the number itself
//System.out.println(multiple1+" is not a factor of a");
}
if(multiple1==a){
d=1;
}
*commented the original code
*/
int factor=1,d=0,a=20; //multiple rephrased as factor
while(a/2>=factor){ //re-arranged your while condition
factor++;
if((a%factor==0))
d++; //increment factor count whenever a factor is found
}
System.out.println("Total number of factors of a : "+(d+2)); // 1 and 'a' are by default factors of number 'a'
}
}
To find all factors inlcuding 1 and the number itself you can do something like below:
//Iterate from 2 until n/2 (inclusive) and divide n by each number.
//Return numbers that are factors (i.e. remainder = 0). Add the number itself in the end.
int[] findAllFactors(int number) {
int[] factors = IntStream.range(1, 1 + number / 2).filter(factor -> number % factor == 0).toArray();
int[] allFactors = new int[factors.length+1];
System.arraycopy(factors,0,allFactors,0,factors.length);
allFactors[factors.length] = number;
return allFactors;
}
To find only prime factors you can do something like this:
//Iterate from 2 until n/2 (inclusive) and divide n by each number.
// Return numbers that are factors (i.e. remainder = 0) and are prime
int[] findPrimeFactors(int number) {
return IntStream.range(2, 1 + number/ 2).filter(factor -> number % factor == 0 && isPrime(factor)).toArray();
}
Helper method for primality check:
//Iterate from 2 until n/2 (inclusive) and divide n by each number. Return false if at least one divisor is found
boolean isPrime(int n) {
if (n <= 1) throw new RuntimeException("Invalid input");
return !IntStream.range(2, 1+n/2).filter(x -> ((n % x == 0) && (x != n))).findFirst().isPresent();
}
If you are not on Java 8 and/or not using Lambda expressions, a simple iterative loop can be as below:
//Find all factors of a number
public Set<Integer> findFactors(int number) {
Set<Integer> factors = new TreeSet<>();
int i = 1;
factors.add(i);
while (i++ < 1 + number / 2) {
if ((number % i) == 0) {
factors.add(i);
}
}
factors.add(number);
return factors;
}
public class Abc{
public static void main(String...args){
if(args.length<2){
System.out.println("Usage : java Abc 22 3");
System.exit(1);
}
int no1=Integer.parseInt(args[0]);
int no=Integer.parseInt(args[1]),temp=0,i;
for(i=no;i<=no1;i+=no){
temp++;
}
System.out.println("Multiple of "+no+" to get "+no1+" is :--> "+temp);
//System.out.println(i+"--"+no1+"---"+no);
System.out.println("Reminder is "+(no1-i+no));
}
}
public class DiceLoop {
public static void main(String[] args) {
// TODO Auto-generated method stub
int die1;
int die2;
int roll = 0;
int count = 0;
while(roll != 2 || roll != 12) {
die1 = (int)(Math.random()*6 + 1);
die2 = (int)(Math.random()*6 + 1);
roll = die1 + die2;
count = count + 1;
System.out.println("Die 1: " + die1);
System.out.println("Die 2: " + die2);
System.out.println("Total: " + roll);
if(roll == 2 || roll == 12){
System.out.println("Stop rolling the dice. 2 or 12 has been thrown.");
}
else {
}
}
}
}
I cannot figure out why my my program runs as an infinite loop. I think that it may be a problem with my else statement, but I can't get the dice to stop rolling.
After a quick look, I believe changing || (logical OR) to && (logical AND) will fix the problem.
public class DiceLoop
{
public static void main(String[] args)
{
int die1;
int die2;
int roll = 0;
int count = 0;
while(roll != 2 && roll != 12)
{
die1 = (int)(Math.random()*6 + 1);
die2 = (int)(Math.random()*6 + 1);
roll = die1 + die2;
count = count + 1;
System.out.println("Die 1: " + die1);
System.out.println("Die 2: " + die2);
System.out.println("Total: " + roll);
if(roll == 2 || roll == 12)
{
System.out.println("Stop rolling the dice. 2 or 12 has been thrown.");
}
else
{
}
}
}
}
For explanation, see #drewmoore's answer.
#Nikola, #ifLoop #StephenC are all correct, but I think the the clearest way to illustrate why they're correct is with a truth table:
roll = 2 roll = 12 (roll != 2 || roll != 12) (roll != 2 && roll != 12)
F F T T
F T T F
T F T F
T T F F
Written with the logical OR (||), this statement is only false when roll is both 12 AND 2 - which of course isn't possible, so it's always true and you've got an infinite loop. With the logical AND, the statement is true when roll is not 12 AND not 2, and otherwise (if it's 2 OR 12 OR both (who knows, maybe that's possible in some other universe)), its false, which is what you want.
The problem is here:
while(roll != 2 || roll != 12)
Think about it.
If roll is 2, it won't be 12, and therefore false OR true is true
If roll is 12, it won't be 2 and therefore true OR false is true
If roll is anything else, true OR true is true.
In short, there is no value for roll that will result in roll != 2 || roll != 12 evaluating to false. Thus you get an infinite loop.
It's your while condition:
while(roll != 2 || roll != 12)
In words: While the roled number is not 2 or 12. That can never evaluated to false!
Use && (logical and) instead of || (logical or)
The definition of do while loop
The while statement continually executes a block of statements while a
particular condition is true. Its syntax can be expressed as:
while (expression) {
statement(s)
}
Let's take a look at your while loop
while(roll != 2 || roll != 12)
Imagine, value of roll is either 2 or 12. Let's assume is 2
while(2 != 2 || 2 != 12)
^ ^
false true
therefore
while(true)
why?
Because of logical OR, so as you see this loop never ends because based on the while definition, The while statement continually executes a block of statements while a particular condition is true.
If you change logical OR to logical AND
while(2 != 2 && 2 != 12)
^ ^
false true
therefore
while (false)
and it is end of the of your loop based on the while definition.
I've been working on Project Euler #7, and can't figure out why my program is not working. The problem is as follows:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
This is my program so far:
public class Euler7 {
public static void main (String[] args) {
long count = 1;
long primes = 0;
while (primes <= 10001) {
if (isPrime(count)){
primes++;
if (primes == 10001) {
System.out.println(count);
}
}
count++;
}
}
public static boolean isPrime (long i) {
if (i <= 1) return false;
else if (i == 2 || i == 3) return true;
else if (i % 2 == 0 || i % 3 == 0) return false;
else {
for (int n = 3; n < Math.sqrt(i); n+=2) {
if (i % n == 0) {
return false;
}
}
return true;
}
}
}
EDIT: To be clear, it returns the value 104033, but WolframAlpha says the 10001st prime is 104743
Your code incorrectly believes that some full squares of primes are prime as well. In particular, your isPrime(25) returns true.
This should be enough to figure out a fix (ok, one more hint: all you need is adding a single character).
when I run this program it get stuck in a loop of asking me to "Enter Value: " and continues to add one to the sum. Although this is exactly what it is supposed to do, if I enter a number that is divisible by 6 or 17 the loop doesn't end. Can explain why?
import java.util.Scanner;
public class DivisibleBy6or17 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter Value: ");
int one = in.nextInt();
int sum=0;
while (one % 6 != 0||one % 17 != 0) {
System.out.print("Enter Value: ");
one = in.nextInt();
sum++;
}
System.out.print("Numbers read: " + sum);
}
}
You should use "&&" instead of "||":
while (one % 6 != 0 && one % 17 != 0) {
Your old condition only stops the loop if the number if divisible by 6 and 17.
In this conditional, you are using an OR; to leave the while loop, you would have to have both one % 6 == 0 and one % 17 == 0. If you enter 102, you should leave the loop.
To fix, use && instead of ||.
The condition has an error, the correct condition is:
while(!(one % 6 == 0 || one % 17 == 0))
or
while(one % 6 != 0 && one % 17 != 0)
I think you will have to use Short-Circuit And instead of OR.
while (one % 6 != 0 && one % 17 != 0)
This is just a suggestion, but why don't you try to create a method that will do the task you are attempting to do rather than put the codes in the main method. The reason for this is to practice re-usability. Here is what I mean:
public static void main(String[] args) {
//Enter code here
//Method Calls here
}
public someMethod here(arguements if needed)
{
//Body here
}