I would like to have a program that show range in specific range and show "no primes" once only if there is no primes in that range like 24 to 28.
int count=0;
for(prime = lowerLimit ;prime < upperLimit; prime++)
{
count=0;
for(divisor = 2; divisor <prime; divisor++)
{
if(prime % divisor== 0)
count++;
}
if(count==0)
System.out.println(prime);
}
if (count>0)
System.out.println("nope");
I have tried to put
if (count>0)
System.out.println("nope");
outside the loop,however it also prints when the range having primes.
How can i tackle it?
Keep one extra variable like noOfPrime, which will count the number of prime number with in a range. And increase by 1 if you found any prime, so that out side of loop you could determine the number prime number as well there is any prime number or not.
int count = 0;
int noOfPrime = 0;
...
for(prime = lowerLimit ;prime < upperLimit; prime++){
...
if(count==0){
System.out.println(prime);
noOfPrime+=1;
}
}
if(noOfPrime >0)
System.out.println("no primes);
First of all, your method for detecting primes is terrible. It works, but it's super slow. I'd suggest you look into using sieves if you want to improve that inner loop.
Secondly, what exactly are you trying to count? Right now your count variable stores the amount of divisors a number has, and then you set it to zero when you check the next number. How is that going to tell you anything about how many primes you have in a certain range? You can just do something like this:
notPrime = false;
for(prime = lowerLimit ;prime < upperLimit; prime++)
{
for(divisor = 2; divisor <prime; divisor++)
{
if(prime % divisor== 0){
notPrime = true;
break;
}
if(notPrime)
break;
}
if(notPrime) System.out.println("There's a prime");
You could design a function to determine if a number is prime something like:
//checks whether an int is prime or not.
boolean isPrime(int n) {
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
and within a for loop, you call the function to each element of the interval:
for(int i=lowerLimit;i<=upperLimit;i++){
if (!(isPrime(i))){
System.out.println("nope");
break;
}
}
Sorry if I have some syntactic errr, I replied from the cell phone.
Everytime you get to the end of the outer loop and count is still 0, it means that you've found a prime number. So if this happens even once, then you're not going to print "nope" at the end. Use a boolean variable to keep track of whether or not you've seen a prime. Since this is homework, I'll let you figure out exactly how to use it. Hint: declare the boolean above both loops.
Related
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
Is there any better logic that can be applied to magic numbers?
Or is there a magic number that I am missing out on?
Please help me out with this simplest working code!
A Magic number is a number whose sum of digits eventually leads to 1.
Example#1: 19 ; 1+9 =10 ; 1+0 = 1. Hence a magic number.
Example#2: 226; 2+2+6=10; 1+0 =1. Hence a magic number.
Example#3: 874; 8+7+4=19; 1+9=10; 1+0=1. Hence a magic number.
boolean isMagic ( int n ) {
return n % 9 == 1;
}
Well, I'm not 100% that the code you placed would work to get a "magic number", but my approach to the problem would be different.
First, I'd receive a String, so that I can get the different digits of the number with a String.charat.
Then I'd use a while cycle to sum the numbers until it gets a single digit number, then check if it's 1.
The code would be
boolean isMagicNumber(String number) {
int[] digits = new int[number.length()];
int sum = 99;
while(sum/10 >= 1) {
sum = 0;
for(int i = 0; i < number.length(); i++) {
sum += Integer.parseInt(""+number.charAt(i));
}
if(sum == 1) {
return true;
}
}
return false;
}
There might be a better solution, but this is what I'd do to solve the problem.
I am trying to print out all the prime factors of a number. My code is as follows:
public static boolean isPrime(long n){
long i = n;
while (i > 0){
if (n % i == 0 && !(i == 1 || i == n)){
return false;
}
i--;
}
return true;
}
public static void primeFactors(long n){
long i = n;
while (i > 0){
if (isPrime(i)){
System.out.println(i);
}
i--;
}
}
This code works for small numbers: 5, 5000,e.g. When I input 600851475143 to the method, my program runs and nothing is output. Why is this happening?
Your primality test function is horrible.
Quick win: count forwards not backwards. Currently you'll count through at lease half your number until you find a factor! That probably accounts for the delay you are observing.
Bit better: count odd numbers up to the square root.
Perhaps better still: count prime numbers up to the square root. precompute those using a sieve depending on the requirements.
The other answers have focused on your function isPrime, which is inefficient. I will instead focus on your function primeFactors which is incorrect. Indeed, you can see that it prints primes up to n in reverse order, rather than the prime factors of n. Instead, do
public static void primeFactors(long n) {
// Handle factors of 2
while (n%2==0) {
System.out.println(2);
n /= 2;
}
// Handle all odd prime factors except the largest
for (long p = 3; p*p <= n; p += 2) {
while (n%p == 0) {
System.out.println(p);
n /= p;
}
}
// Handle the largest prime factor
if (n > 1) {
System.out.println(2);
}
}
You might notice that isPrime is never used! In fact it is not needed: as long as they are removed as you find them, all of the numbers you print will be primes.
There are many possible improvements here, but this method is fast enough as-is. One simple way would be to compute an upper bound of Math.sqrt(n) and compare p to it rather than multiplying p by itself each time. You might also want to check for 0 and negative numbers, and possibly 1, depending on how you want to handle those numbers.
When given the input number 600851475143, your program is printing nothing because the way you check for prime numbers is slow. Given enough patience, your program will print something - but this could be hours, days, even years. You would need to come up with a better algorithm for this calculation.
Short answer: the program actually isn't terminating. The method that you are using is one of the most inefficient ways to check for primes. Check out the Sieve of Eratosthenes for an easy to understand, fairly efficient algorithm.
no need to check n numbers to check if n is prime or no, It's enough to start from 0 to n/2:
public static boolean isPrime(long n){
long i = 2;
while (i < n/2){
if (n % i == 0 ){
return false;
}
i++;
}
return true;
}
This will double performance
Although the number is not out of long primitive value range (9,223,372,036,854,775,807), you should use BigInteger since BigInteger has function for this purpose and I think it is more efficient then other implementations including yours.
new BigInteger(yourNumer).isProbablePrime(100) // returns true or false
Furthermore primality test is done by using many mathematical approaches and algorithms, there are some ways which runs faster for numbers < 64bit and there are some which are better to test much larger numbers. There some other ways here
Change your method to the following:
public static boolean isPrime(long num) {
for (int i = 2; i < Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
Should be efficient enough.
I am a novice, please excuse my lack of organization.
Okay, so what I did was I made an array filled with all the prime numbers between 8 and 100. What I want to do now is make another array that finds all the prime numbers between 101-200. So allow me to explain how I did the first part:
//Prime1 is an dynamic integer array which stores all the prime numbers between 8 and 100
int arrayCounter = 0;
for(int primeTest = 8; primeTest<=100; primeTest++)
{
if(primeTest%2!=0 && primeTest%3!=0 && primeTest%5!=0 && primeTest%7!=0)
{
Prime1.add(primeTest); //adds the prime numbers to array
arrayCounter = arrayCounter +1;
}
else
{
arrayCounter = arrayCounter + 1;
}
}
Now back to the main issue, rather than writing "if(primeTest % "prime#" !=0)" I would like to be able to use modulus through the entire Prime1 array and see if all the values do not equal zero... Let me elaborate.
for(int primeTest2 = 101; primeTest2 <= 200; primeTest2++)
{
for(int arrayCounter2 = 0; arrayCounter2 < Prime1.size(); arrayCounter2++)
{
if(primeTest2 % Prime1.get(arrayCounter2) != 0 )
{
Prime2.add(primeTest2);
}
}
}
//please forgive any missing braces
^^So what happens here is that I take a value starting at 101 and modulus it with the first value of the Prime1 array. As you know, this may give me a false positive because 11 (the first prime number in the array) may still show true even with numbers which are not prime. This is why I need to be able to test a number with all the values in the array to ensure that it cannot be divided by any other prime number (meaning that it is prime).
Your method is extremely inefficient, nevertheless, here is how you can fix it:
for (int primeTest2 = 101; primeTest2 <= 200; primeTest2++)
{
boolean prime = true;
for (int arrayCounter2 = 0; arrayCounter2 < Prime1.size(); arrayCounter2++)
{
if (primeTest2 % Prime1.get(arrayCounter2) == 0)
{
prime = false;
break;
}
}
if (prime)
Prime2.add(primeTest2);
}
BTW, for the first set of prime numbers, it is sufficient to use 2, 3, 5, 7, 11, 13.
Take a boolean and set it to true. If the number can be divided by any of your primes from 8 to 100 without a remainder, than set it to false. If it is still true after testing every number, add the tested number to the Prime2 array, otherwise continue with the next number. Example:
for(int n = 101; n <= 200; n++)
{
boolean isPrime = true;
for(Integer p : Prime1)
if(n % p == 0 )
{
isPrime = false;
break;
}
if(isPrime)
Prime2.add(n);
}
But there are better alorithms out there to check if a number is prime or to calculate alle primes below n. For example the Sieve of Eratosthenes.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How would you modify the below to print out all prime numbers from 1-100? The below has an issue with the number 2 coming back as not prime. The if(i%number == 0) condition is met for the number 2 as 2%2 is returned as 0.
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
for(int i=1; i<=100; i++){
if(isPrime(i)){
System.out.println(i + " is a prime number");
}else{
System.out.println(i + " is not a prime number");
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<=number; i++){
if(i%number == 0){
return false;
}else{
return true;
}
}
return false;
}
}
i<=number
You shouldn't be checking whether the number is divisible by itself.
You also have another problem:
}else{
return true;
}
You're returning true as soon as you find a single non-divisible number, even if it does have factors later.
Here is an algorithm for determining whether or not a number is prime.
Is the number less than 2? If so, return false.
Is the number 2 or 3? If so, return true.
Is the number 4? If so, return false.
Take the square root of the number, rounded up to the next integer. This is optional for small prime numbers, but speeds up the determination for larger numbers.
Loop from 5 to the square root of the number (or the number), incrementing by 2.
Divide the loop number by the prime numbers determined so far.
If the modulus of the division is zero, return false.
If the loop is completed, return true.
You've got a couple issues here. Firstly, when checking whether or not a number is prime, never check every number up to the actual number being checked for primality. A check of all primes up to the square root of the number will always be sufficient.
To fix that error look at your for loop condition and edit it accordingly:
for(int i=2; i<=number; i++)
Secondly, when a function returns it stops. Currently with your if/else statement:
if (i%number == 0) {
return false;
} else {
return true;
}
If this condition goes to the else statement even once it will return true, you want to make sure you only actually return true when you've checked all of the numbers you intend to.
Additionally I don't think you've carefully considered what you base case is. What you are saying with your last line is that if everything previously slipped through the cracks then it should assume the number isn't prime. Think about it and I'm sure you'll be able to figure it out.
This will work. 2 is a special case when testing for primes. If you start to search a larger and larger...you might want to look at the sieve of eratosphenes.
Every prime number is a multiple of another number. Take 3 for example. Using the sieve, if you find 3 to be prime it will then 'ignore' all multiples of 3 thus reducing the amount of time taken to find consequent primes. It speeds things up...ALOT :)
public class JavaApplication47 {
public static void main(String[] args) {
for(int i=1; i<=100; i++){
if(isPrime(i)){
System.out.println(i + " is a prime number");
}else{
// System.out.println(i + " is not a prime number");
}
}
}
public static boolean isPrime(int n) {
for(int i=2; 2*i<n; i++) {
if(n%i==0)
return false;
}
return true;
}
}
SIEVE EXAMPLE - NOT IMPLEMENTED - Can be used for reference and understanding.
static boolean [] allPrimes = new boolean[10000];
public static void fillTheSieve(){
Arrays.fill(allPrimes, true);
allPrimes[0] = allPrimes[1] = false; //1 and 0 are false. winning
for (int i = 2; i < allPrimes.length; i++) {
//check if prime, if so getmultiples and declae false
if(allPrimes[i]){
for (int j = 2; i*j<allPrimes.length; j++) {
allPrimes[i*j] = false;
}
}
}
}
The definition of a prime number specifically states that one cannot be a prime number.
That means that isPrime(1) should return false. Which your implementation does.
But isPrime(2) should return true. Which your implementation does not. It does not because (2 % 2 == 0) and you are checking all numbers from 2 to N, not from 2 to N-1. The last number, N, will always yield a zero remainder (N % N == 0)
Just a few things to think about when dealing with Primes. You can have a special case for 2 at the start (i.e. something like if(number == 2)...).
In addition to your error in checking all the way to i<=number consider only how far you need to go in order to be certain it is not prime, hints have already been given with i*i or Math.sqrt
Another thing in the increment i++ think about what that entails, I realize this is only for the first 100 primes but you should always be thinking about performance. Do you really have to check all numbers (2,3,4,5,6...) (hint: if you have checked if its divisible by 2 then you dont need to check for 4,6,8 etc..)
Finally with your return statements, consider using a boolean flag that you set to false/true only when you are positive the number is a prime or is not. And you only need to use 1 return statement.
Hope that helps.
Please try this
public static boolean isPrime(int number) {
for(int i = 2; i * i <= number; i++) {
if (i % number == 0) {
return false;
} else {
return true;
}
}
return true;
}