static void primeNumbers(int n)
{
System.out.println("All the prime numbers up to "+n+" are -->\n");
boolean isPrime = true;
for(int i = 2; i < n; i++)
{
for (int j = 1; j < i; j++)
{
if(i % j == 1)
{
isPrime = true;
System.out.print(j);
}
if(i % j == 0)
{
isPrime = false;
System.out.print(" ");
}
}
}
}
In this code I am trying to list all the prime numbers up to 'n' which is the number the user inputs. I am confused as to how to fix this to produce all of the prime numbers up to n.
You want to test if i is dividable by any number in the range of [2..i-1] and if it is, then it is not a prime number. Your j-loop starts at 1, that is the first error.
Knowing when a number is dividable by another is tested like this: if (i % j == 0) { (if the division remainder is zero) where in your code you test for equality with 1 instead.
Third thing is that you make your decision in the first iteration (when j is 1) and always print something in your inner loop. You need to take the logic out of the inner loop. Only if i is not dividable by any of the js then it is prime.
Here is a modified version of your code:
static void primeNumbers(int n) {
System.out.println("All the prime numbers up to "+n+" are -->\n");
for (int i = 2; i < n; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if(i % j != 0) {
isPrime = false;
}
}
if (isPrime) {
System.out.print(i, " ");
}
}
}
if (i % j == 0) {
isPrime = false;
System.out.print(" ");
}
This if statement is always true for any i because j starts at 1. As a result, you print a space for every number < n and >= 2
Also, isPrime may be an unnecessary variable.
Your algorithm, although slow, seems to be correct on most parts except for the fact that you are not handling the boundary conditions well. E.g. 2 is a prime number, you are running iterations only till n-1, you are not reseting the isPrime flag for every number, and a few small things. Here's a revised working version. Try to compare it with yours and understand where you didn't get it right.
int n = 10;
System.out.println("All the prime numbers up to "+n+" are -->\n");
boolean isPrime = true;
for(int i = 2; i <= n; i++)
{
for (int j = 2; j < i; j++)
{
if(i % j == 0)
{
isPrime = false;
break;
}
}
if(isPrime) {
System.out.println(i);
}
isPrime = true;
}
Don't re-set isPrime to true in your second for loop, as soon as the number is not prime once, we know it is not prime forever. Just set it to true once every iteration of the outer loop, and do your final "Is prime" check outside.
static void isPrime(int n)
{
System.out.println("All the prime numbers up to "+n+" are -->\n");
for(int i = 2; i <= n; i++)
{
boolean isPrime = true;
for (int j = 2; j < i; j++)
{
if(i % j == 0)
{
isPrime = false;
System.out.println(i + " is not prime because " + i + " is divisible by " + j );
break;
}
}
if (isPrime){
System.out.println(i + " is prime.");
}
}
}
I've added a couple prints to this code so that you can see why each part of the logic is doing what it does -- compare it to your code so that you can understand why yours doesn't actually search for primes.
I think is a logical problem in your script.
You should count with a loop all the number from 2 to n-1 which are = to 0 with a test
n%i = 0
If the counter = 0 then no divider then prime number
Related
What I need it to do is print all of the prime numbers starting at 1 and ending at the input, if the input is also a prime number. Here's my code now:
static void primeNumbers(int n) {
boolean isPrime;
System.out.println("All the prime numbers up to " + n + " are -->");
for (int prime = 2; prime < n; prime = prime++) {
if (n % prime == 0) {
isPrime = false;
}
if(isPrime == true){
System.out.println(prime);
}
}
}
My teacher said that I need to make a nested for loop, but I just don't know what to put in it. I'm also getting an error saying that my last use of isPrime hasn't been initialized.
You need to actually check for primality, and not just see if the number is a factor of n:
static boolean isPrime(int n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
for (int k = 3; k * k <= n; k += 2) {
if (n % k == 0) {
return false;
}
}
return true;
}
static void primeNumber(int n) {
System.out.println("All the prime numbers up to " + n + " are -->");
for (int num = 2; num < n; num ++) {
if (isPrime(num)) {
System.out.println(num);
}
}
}
You will need to do something like this for your program to work.
static void primeNumbers(int n) {
boolean isPrime = true;
System.out.println("All the prime numbers up to " + n + " are -->");
for (int prime = 2; prime < n; prime++) {
if (n % prime == 0) {
isPrime = false;
}else{
isPrime = true;
}
if(isPrime){
System.out.println(prime);
}
}
}
It is necessary to initialize isPrime.
And, Eratosthenes' s sieve is famous algorithm for get prime numbers.
I think the URL below will help you.
https://www.geeksforgeeks.org/java-program-for-sieve-of-eratosthenes/
here is one of the solutions
public static void main(String[] args) {
int n = 23;
boolean[] isPrime = new boolean[n + 1];
for (int i = 1; i <= n; i++) {
isPrime[i] = true;
}
for (int i = 2; i <= n / i; i++) {
if (isPrime[i]) {
for (int j = i; j <= n / i; j++) {
isPrime[i * j] = false;
}
}
}
for (int i = 1; i <= n; i++) {
if (isPrime[i]) {
System.out.println(i);
}
}
}
I am trying to print last three prime numbers less than 100. If I print less than 10 prime number it is working correctly. But when I try to print less than 100 it is not working correctly. I don't know why. Can you tell me an efficient way to print last three numbers?
int[] a = new int[100];
int flag=0,c=0,i=2,j=2;
int n=10;
while(i <= n)
{
flag=0;
while(j<=i/2)
{
if(i%j==0)
{
flag=1;
break;
}
j++;
}
if(flag==0)
{
a[c]=i;
c++;
}
i++;
}
for(i=0;i<c;i++)
{
c--;
System.out.print(a[c]+" ");
}
First you have to re-init the variables j and flag.
while(i <= n) {
//...
if(flag==0) {
a[c]=i;
c++;
}
i++;
j = 2;
}
You can show the last three prime like this
for(i = c-1; i >= c-3; i--) {
System.out.print(a[c]+" ");
}
Or you can use this code
int numToShow = 3, n = 100;
boolean isPrime = true;
while(n > 1 && numToShow > 0) {
for (int j = 2; j <= (int) Math.sqrt(n) && isPrime; j++) {
if(n % j == 0) {
isPrime = false;
}
}
if (isPrime) {
System.out.print(n + " ");
numToShow--;
}
isPrime = true;
n--;
}
My code in Java:
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Введите целое число: ");
int n = scanner.nextInt();
boolean isPrime = false;
for (int i = 2; i <= n; i++) {
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
} else {
isPrime = true;
}
}
if (isPrime) {
System.out.println(i);
}
}
}
}
But my teacher said that I should move the boolean variable into the loop. This will simplify the code.
But I do not understand how to do it.
What your teacher is saying is that this line:
boolean isPrime = false;
Needs to be moved into the loop where the comments are. You are clearly looking for all prime numbers between 2 and n. Your loop variable 'i' is the prime-number to test, and whether it is prime or not, needs to be initialized to false every time you start an iteration test.
for (int i = 2; i <= n; i++) {
// NEEDS TO BE RIGHT HERE -
boolean isPrime = true;
// You are finding Prime Numbers, and the outer-loop (loop-var 'i')
// Means the 'isPrime' needs to be re-initialized each time you start testing
// whether a certain number, i, is prime or not!
for (int j = 2; j < i; j++)
if (i % j == 0) { isPrime = false; break; }
// and this line needs to be removed completely.
// else { isPrime = true; }
if (isPrime) System.out.println(i);
}
I created this loop to find prime numbers, the int num is initialized as 0, but the debugger always skips 1 (which is correct) and 2 (which is not correct).
How does it come that it always skips 2 % 2 == 0 ?
for (int num = 0; num <= 100; num++) {
for (int j = 2; j < num; j++) {
if (num % j == 0) {
System.out.println(num + " is not a prime number.");
break;
}
if (num - j == 1) {
System.out.println("PRIME NUMBER FOUND! It's: " + num + ".");
myPrimeNumbers.add(num);
}
}
}
The problem with your code is that in the case num=2 you don't get into the part where you add the prime number. You chose to use the last iteration of the inner loop as the place where to add a prime number to your list, but with num=2 the inner loop has 0 iterations.
I'd modify your program as follows:
package test;
import java.util.ArrayList;
import java.util.List;
public class Test {
private static boolean isPrime(int num) {
for (int j = 2; j < num; j++) {
if (num % j == 0) {
return false;
}
}
return true;
}
public static void main (String [] args) {
List<Integer> myPrimeNumbers = new ArrayList<>();
for (int num = 2; num <= 100; num++) {
if (isPrime(num)) {
System.out.println("PRIME NUMBER FOUND! It's: " + num + ".");
myPrimeNumbers.add(num);
}
}
}
}
Extracting the prime test into a method makes it easy to place the true and false returns at locations where they are intuitively correct.
And I started the prime number search with 2 instead of 0 as we all know that 0 and 1 are by definition no primes.
Write a program that prompts the user for an integer and then prints out all prime numbers up to that integer. For example, when the user enters 20, the program should print
2 3 5 7 11 13 17 19
Recall that a number is a prime number if it is not divisible by any number except 1 and itself.
I am trying to write this program but I am having difficulties, can anyone show me how to write this code?
This is what I have written but it is completely wrong.
import java.util.Scanner;
public class PrimeNumbers
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter Integers: ");
int x;
int n = in.nextInt();
for (int i = 2; i < n ; i++)
{
x = i;
if (n % i != 0 && i % x != 0)
{
System.out.println(i);
}
x--;
}
}
}
Computes the number of primes less than or equal to N using
the Sieve of Eratosthenes.
% java PrimeSieve 25
The number of primes <= 25 is 9
% java PrimeSieve 100
The number of primes <= 100 is 25
% java -Xmx100m PrimeSieve 100000000
The number of primes <= 100000000 is 5761455
% java PrimeSieve -Xmx1100m 1000000000
The number of primes <= 1000000000 is 50847534
The 110MB and 1100MB is the amount of memory you want to allocate
to the program. If your computer has less, make this number smaller,
but it may prevent you from solving the problem for very large
values of N.
class PrimeSieve {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= N; i++) {
if (isPrime[i]){ primes++; System.out.print(i+", ");}
}
System.out.println("\nThe number of primes <= " + N + " is " + primes);
}
}
Use this method to check if a given int is a prime.
public static boolean isPrime(int a)
{
if ( a == 2)
return true;
int midpoint = Math.round(a/2);
for(int i = 2; i < midpoint; i++)
{
if(a % i == 0)
return false;
}
return true;
}
Explanation:
Loop through all the numbers until midpoint and modulus until you encounter 0 or not. If you encounter 0 then return false because we know that it is not prime, if we encounter no zero then we return true because it is prime.
We loop until midpoint because there is no need to loop further.
You can implement it in your loop via
for (int i = 2; i < n ; i++)
{
if (isPrime(i))
{
System.out.println(i);
}
}