This is a basic prime number checker. How would I loop this code so it tells me every single number from 1 to 100 and if its prime or not. For example:
1 is not a prime number
2 is a prime number
3 is a prime number
and so on until 100. This is not a user generated program just straight up if I run it it gives me all 100 numbers
int check;
int number;
boolean prime = true;
for (int i=2; i<=check/2; i++)
{
number = check%i;
if (number == 0)
{
prime = false;
}
}
if (prime == true)
{
System.out.println(check + " is a prime number");
}
else
{
System.out.println(check + " is not a prime number");
}
}
You have almost all of the code correct, you just need to put it in the right place. For example, your println statements need to be inside the for loop and your for loop needs to start at 1 and increment by 1 to 100.
for(int x = 0; x < 101; x++)
{
if(x == 2)
System.out.println(x + " is a prime number");
if(x % 2 == 0)
System.out.println(x + " is not a prime number);
else
System.out.println(x + " is a prime number);
}
I just helped a friend with almost this exact problem, so this couldn't be better timing. I don't know if your scanner is going to be used, but this works if you are just looking for prime numbers from 1-100.
For starters, it seems your Scanner isn't being used anywhere. Maybe your code is incomplete?
You can replace the Scanner part where you get the input from the user with a for loop that will give the number to you. Like so:
for(int number = 1; number <= 100; number++) {
// code for checking if number is prime or not
}
Take a look at code below, let me know if something is unclear, ask, don't just read and copy:
package com.company;
public class Main {
public static void main(String[] args) {
out:
for (int i = 1; i <= 100 ; i++) {
for (int j = 2; j <= i / 2 ; j++) {
if (i % j == 0) {
System.out.println(i + " is not prime number.");
continue out;
}
}
System.out.println(i + " is prime number.");
}
}
}
So to just walk over the code real quick:
1.) Create labeled block called out:
out:
2.) Create two nested for loops to check for our numbers being prime or not
3.) If statement in the second for loop will check if our number is not prime (if it's divisible by any number from 1 to itself but not those two numbers)
4.) In case our evaluation in if statement is false we continue looping until our second loop condition fails, then we move outside of the loop and print that number is prime:
System.out.println(i + " is prime number.");
5.) In case our evaluation in if statement is true we enter the if block, we print that number is not prime and we move program control back to the labeled block we created earlier
6.) We continue doing this repeatedly until outter loop check condition fails and our program is done with it's work.
/* Prime numbers are numbers that are divisible by 1 and by themselves. So, if you take the modulus of a number 'N' with all the number from 1 till 'N' and increase a count each time the modulus is zero, you can use a simple if condition at the end to check whether they are prime or not. In this code, I start from checking with number 1 and go till 100*/
int count ;
for(int j=1;j<=100;j++)
{
count=0;
for(int i=1;i<=j;i++)
{
if(j%i==0)
count=count+1;
}
if(count>2)
System.out.println(j+"is not a prime number");
else
System.out.println(j+"is a prime number");
}
Related
The problem is to check a random number n can be the sum of 2 random prime numbers. For example,
if n=34 the possibilities can be (3+31), (5+29), (17+17)...
So far I have managed to save prime numbers to the array, but have no clue how I could check, if n is the sum of 2 prime numbers.
This is part of my code:
public static void primeNumbers(int n) {
int i = 0, candidate = 2, countArray = 0, countPrime = 0;
boolean flag = true;
while (candidate <= n) {
flag = true;
for (i = 2; i < candidate; i++) {
if ((candidate % i) == 0) {
flag = false;
break;
}
}
if (flag) {
countPrime++;
}
candidate++;
}
int[] primeNumbers = new int[countPrime];
while (candidate <= n) {
flag = true;
for (i = 2; i < candidate; i++) {
if ((candidate % i) == 0) {
flag = false;
break;
}
}
if (flag) {
primeNumbers[countArray] = candidate;
}
candidate++;
countArray++;
}
for (i = 0; i <= primeNumbers.length; i++) {
}
}
First I counted how many prime numbers are between 1-n so I can declare and initialize my array for prime numbers. Then I save prime numbers to the array. But now I have no idea how I could check if n is the sum of 2 prime numbers.
Given that you already have list of "prime numbers less than the given number", It is a very easy task to check if two prime numbers can sum to given number.
for(int i=0; i<array.length; i++){
int firstNum = array[i];
int secondNum = givenNum - firstNum;
/* Now if it is possible to sum up two prime nums to result into given num, secondNum should also be prime and be inside array */
if(ArrayUtils.contains(array, secondNum)){
System.out.println("Yes, it is possible. Numbers are "+ firstNum + " and " + secondNum);
}
}
EDIT: ArrayUtils is part of Apache Commons Lang library
You can however use ArrayList instead to use contains method.
You do not have to check all prime numbers from 1 to the given number or you don't even need an array.
Algorithm one can be;
First of all write a function that checks whether a given number is prime.
Split the number into two parts, 0 and the remaining value(the number itself). Now start decreasing the number part by 1 and start adding 1 to 0 simultaneously. Stop when the number part which we are decreasing becomes 0 or both the parts are prime numbers.
Another algorithm can be like this;(It is similar to the accepted answer)
Start subtracting prime numbers from the given number starting from 2.Check whether the subtraction is also prime.
The time you get the subtraction as a prime number, stop , you have got the two prime numbers that sum up to the given number.
Okay my issue is less of how to figure out if a number is prime, because I think I figured that out, but more of how to get it to display properly.
Here's my code:
public static void main(String[] args) {
// Declare Variables
int randomNumbers = 0;
int sum = 0;
//Loop for number generation and print out numbers
System.out.print("The five random numbers are: ");
for (int i = 0; i <= 4; i++)
{
randomNumbers = (int)(Math.random()*20);
sum += randomNumbers;
if (i == 4) {
System.out.println("and " + randomNumbers + ".");
}
else {
System.out.print(randomNumbers + ", ");
}
}
//Display Sum
System.out.println("\nThe sum of these five numbers is " + sum + ".\n");
//Determine if the sum is prime and display results
for(int p = 2; p < sum; p++) {
if(sum % p == 0)
System.out.println("The sum is not a prime number.");
else
System.out.println("The sum is a prime number.");
break;
}
}
}
Now my problem is, if the number ends up being something like 9, it'll say it is a prime number, which it is not. I think the issue is that the break is stopping it after one loop so it's not incrementing variable p so it's only testing dividing by 2 (I think). But if I remove the break point it will print out "The sum is/is not a prime number" on every pass until it exits the loop. Not sure what to do here.
Your method for finding if your number is prime is the correct method.
To make it so that it does not consistently print out whether or not the number is prime, you could have an external variable, which represents whether or not the number is prime.
Such as
boolean prime = true;
for (int p = 2; p < sum; p++) {
if (sum % p == 0) {
prime = false;
break;
}
}
if (prime)
System.out.println("The sum is a prime number.");
else
System.out.println("The sum is not a prime number.");
By doing this method the program will assume the number is prime until it proves that wrong. So when it finds it is not prime it sets the variable to false and breaks out of the loop.
Then after the loop finishes you just have to print whether or not the number was prime.
A way that you could make this loop faster is to go from when p = 2 to when p = the square root of sum. So using this method your for loop will look like this:
double sq = Math.sqrt((double)sum);
for (int p = 2; p < sq; p++) {
//Rest of code goes here
}
Hope this helps
You need to store whether or not the number is prime in a boolean outside of the loop:
//Determine if the sum is prime and display results
boolean isPrime = true;
for(int p = 2; p < sum; p++) {
if(sum % p == 0){
isPrime = false;
break;
}
}
if(isPrime){
System.out.println("The sum is a prime number.");
} else {
System.out.println("The sum is not a prime number.");
}
You are right, currently your code tests dividing by two, and the break command is stopping after one loop.
After the first go of your loop (p==2), the break will always stop the loop.
The fastest fix to your code will change the loop part like this:
boolean isPrime=true;
for(int p = 2; p < sum; p++) {
if(sum % p == 0) {
isPrime=false;
System.out.println("The sum is not a prime number.");
break;
}
}
if (isPrime)
System.out.println("The sum is a prime number.");
This code can be improved for efficiency and for code elegance.
For efficiency, you don't need to check divisibility by all numbers smaller than sum, it's enough to check all numbers smaller by square-root of sum.
For better code, create a seperate function to test if a number is prime.
Here is an example that implements both.
// tests if n is prime
public static boolean isPrime(int n) {
if (n<2) return false;
for(int p = 2; p < Math.sqrt(n); p++) {
if(n % p == 0) return false; // enough to find one devisor to show n is not a prime
}
return true; // no factors smaller than sqrt(n) were found
}
public static void main(String []args){
...
System.out.println("sum is "+ sum);
if (isPrime(sum))
System.out.println("The sum is a prime number.");
else
System.out.println("The sum is not a prime number.");
}
Small prime numbers
Use Apache Commons Math primality test, method is related to prime numbers in the range of int. You can find source code on GitHub.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
// org.apache.commons.math3.primes.Primes
Primes.isPrime(2147483629);
It uses the Miller-Rabin probabilistic test in such a way that a
result is guaranteed: it uses the firsts prime numbers as successive
base (see Handbook of applied cryptography by Menezes, table 4.1 / page 140).
Big prime numbers
If you are looking for primes larger than Integer.MAX_VALUE:
Use BigInteger#isProbablePrime(int certainty) to pre-verify the prime candidate
Returns true if this BigInteger is probably prime, false if it's
definitely composite. If certainty is ≤ 0, true is returned.
Parameters: certainty - a measure of the uncertainty that the caller
is willing to tolerate: if the call returns true the probability that
this BigInteger is prime exceeds (1 - 1/2certainty). The execution
time of this method is proportional to the value of this parameter.
Next use "AKS Primality Test" to check whether the candidate is indeed prime.
So many answers have been posted so far which are correct but none of them is optimized. That's why I thought to share the optimized code to determine prime number here with you. Please have a look at below code snippet...
private static boolean isPrime(int iNum) {
boolean bResult = true;
if (iNum <= 1 || iNum != 2 && iNum % 2 == 0) {
bResult = false;
} else {
int iSqrt = (int) Math.sqrt(iNum);
for (int i = 3; i < iSqrt; i += 2) {
if (iNum % i == 0) {
bResult = false;
break;
}
}
}
return bResult;
}
Benefits of above code-:
It'll work for negative numbers and 0 & 1 as well.
It'll run the for loop only for odd numbers.
It'll increment the for loop variable by 2 rather than 1.
It'll iterate the for loop only upto square root of number rather than upto number.
Explanation-:
I have mentioned the four points above which I'll explain one by one. Code must be appropriately written for the invalid inputs rather the only for valid input. Whatever answers have been written so far are restricted to valid range of input in which number iNum >=2.
We should be aware that only odd numbers can be prime, Note-: 2 is the only one even prime. So we must not run for loop for even numbers.
We must not run for loop for even values of it's variable i as we know that only even numbers can be devided by even number. I have already mentioned in the above point that only odd numbers can be prime except 2 as even. So no need to run code inside for loop for even values of variable i in for.
We should iterate for loop only upto square root of number rather than upto number. Few of the answers has implemented this point but still I thought to mention it here.
With most efficient time Complexity ie O(sqrt(n)) :
public static boolean isPrime(int num) {
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
you can use the Java BigInteger class' isProbablePrime method to determine and print whether the sum is prime or not prime in an easy way.
BigInteger number = new BigInteger(sum);
if(number.isProbablePrime(1)){
System.out.println("prime");
}
else{
System.out.println("not prime");
}
You can read more about this method here https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#isProbablePrime%28int%29
import java.util.*;
//Creates a program which allows the user to find the factorial of a number
public class forLoop {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number you want the factorial from: ");
int number = input.nextInt(); // user input
input.close();
int result_2 = getFactorial(number); //initializes getFactorial method
System.out.println("The factorial of " + number + " is " + result); //prints results
}
public static int getFactorial (int num1) {
int result;
for (int times = num1; times <= 1; times--) { //repeats loop until times <=1
result = num1 * (num1 - 1); //does the factorial equation
}
return result; // returns results (here is the problem)
}
}
The compiler cannot assume that the loop would execute at least once - a necessary condition for the result to get assigned.
Change declaration of result as follows to fix the problem:
int result = 1;
This would help your code compile, but it would not fix the logical error in calculating the factorial: currently, your loop would run indefinitely because of a wrong loop condition.
You should be multiplying numbers from 1 to num1, inclusive. Change the loop condition so times >= 1 instead of times <= 1, and the loop body to result *= times to fix this error.
You need to intialize this variable:
int result;
Like this:
int result = 0; //Which ever intial value you want
Because compiler will not be sure that for loop will be always executed.
The condition of for loop is incorrect
it shoud be
for (int times = num1; times >= 1; times--)
{
result *= times; //this wil calculate right factorial
}
also initialize result to 1 before for loop
since you are assigning the function return value to result_2, you should print that instead of result
try
System.out.println("The factorial of " + number + " is " + result_2);
And you are need to initialize local variable before using them
int result;
for (int times = num1; times <= 1; times--) { //repeats loop until times <=1
result = num1 * (num1 - 1); //does the factorial equation
}
This block is causing the error. If the loop does not run even once due to this
times <=1
condition java wont have anything to print here
System.out.println("The factorial of " + number + " is " + result);
So here comes the need of initialization which acts as a default value to print.
So the solution will be to replace
int result;
with
int result=1; // note that I am not initializing with 0 as that will cause every factorial to become zero.
there is another mistake in your code instead of
times <= 1
it should be
times >= 1
Your code will probably not run even once for this error.
Just initialize int result to something:
int result = 0;
Because your loop isn't executing (times is already greater than 1), it is trying to return an uninitialized variable.
I am having trouble with this simple loop for a uni lab. It wont stop looping until I put in a number over a thousand. I can't see where I have gone wrong on such a simple loop.
I have meant to have written a simple method that will loop through adding numbers until the number is greater than 100 and then once it has reached 100 or greater it will output the total.
public void adder2(){
int sum = 0;
int number = 0;
while(number < 100){
sum = sum + number;
number = getNumber();
}
System.out.println("The result is " + sum);
}
Try this:
while (sum < 100 && number < 100) { ...code as above... }
Hey I am beginning to program using java and my teacher used this example in class for our homework which was to create a java program that prints out every prime number before reaching the upper limit that the user inputs. I am not understanding the second part and wondering if someone could help explaining it to me.
import java.util.Scanner;
public class Primes {
public static void main(String args[]) {
//get input for the upper limit
System.out.println("Enter the upper limit: ");
//read in the limit
int limit = new Scanner(System.in).nextInt();
//use for loop and isPrime method to loop through until the number reaches the limit
for(int number = 2; number<=limit; number++){
//print prime numbers only before the limit
if(isPrime(number)){
System.out.print(number + ", ");
}
}
}
//this part of the program determines whether or not the number is prime by using the modulus
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false; //number is divisible so its not prime
}
}
return true; //number is prime now
}
}
I guess that what you mean by second part is the isPrime method.
What he is doing is using '%' operator which returns the integer remainder of the division between 'number' and 'i'. As a prime number is just divisor for itself and the number 1, if the remainder is 0 it means is not a prime number. Your teacher is looping with the 'i' variable until the limit number and checking if any of the numbers is prime by looking the result of the % operation.
Hope this is helpful for you!!
In the second part
if(number%i == 0)
% usually gives you a remainder if there is.
eg
5 % 2 gives 1
4 % 2 gives 0
for(int i=2; i<number; i++)
Here you are looping through from 2 to the number. Since all numbers are divisible by 1 you start from 2.
Also you stop before number (number -1) since you dont want to check if the number is divisible by itself (because it is).
If a number is divisible by any other number other than 1 and itself (number from 2 to number -1) then it is not a prime number.
Just a short (not efficient) reference for finding prime numbers if you need it:
int upperLimit = 30; //Set your upper limit here
System.out.println(2);
for(int i = 2; i < upperLimit; i++)
for(int j = 2; j < i; j++)
if(i % j == 0 && i != 2)
break;
else if(j == i - 1)
System.out.println(i);