"WAP a program to find prime numbers between between zero and 100" - java

I typed this piece of code for finding all the prime numbers between 0 and 100, but it gives output with multiples of other numbers. How can I rectify this?
public class PrimeNumbers {
public static void main(String[] args) {
int count = 0;
int n = 0;
for (n = 2; count <= 100; n++) {
for (int j = 2; j < n; j++) {
while (n % j == 0) {
j = 2;
n++;
}
}
count++;
System.out.println(n);
}
}
}

Make sure to read the other answers and understand the issue in your code. The error can be fixed with some minor changes:
public class PrimeNumbers{
public static void main(String[] args) {
for (int n = 2; n <= 100; n++) {
boolean isPrime = true;
for (int j = 2; j < n; j++) {
if (n % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(n);
}
}
}
}

Related

how can i determine all prime numbers smaller than a given input value? [duplicate]

This question already has answers here:
Return all prime numbers smaller than M
(9 answers)
Closed 3 years ago.
Can anyone help me to determine all prime numbers smaller than a given input value using scanner with java8 .
Input: N integer> 0
Output: the table with prime numbers.
Example: for N = 10 the Output is : 2 3 5 7
this is my work so far:
class Main {
public static void main(String[] args) {
int N;
int[] result = null;
try (Scanner scanner = new Scanner(new File(args[0]))) {
N = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < (N/2)+1; i++) {
if (N%i==0)
result[i]=i;
for (int j = 0; j < result.length; j++) {
System.out.print(result[j]);
if (j < result.length - 1) {
System.out.print(" ");
}
}
}
System.out.println();
}
catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
}
your code problem is int i = 0 start with 0 and next line if (N%i==0) so 10/0 is not possible throw a error something like java.lang.ArithmeticException: / by zero is not possible
and you loop through result.length, you need to loop through i your parent loop and put condition inside if (N%i==0) and you need many changes saw my below answer and debug where you get unexpected output and follow.
brute Force
public static void main(String[] args) {
int N = 50;
List<Integer> result = new ArrayList<>();
for (int i = 1; i < N; i++) {
boolean isPrime = true;
for (int j = 2; j < i - 1; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result.add(i);
}
}
result.forEach(System.out::println);
}
optimize one using Math.sqrt reason
public static void main(String[] args) {
int N = 101;
List<Integer> result = new ArrayList<>();
for (int i = 1; i <= N; i++) {
boolean isPrime = true;
for (int j = 2; j < Math.sqrt(i - 1); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result.add(i);
}
}
result.forEach(System.out::println);
}
using BigInteger.isProbablePrime see
public static void main(String[] args) {
int N = 101;
List<Integer> result = new ArrayList<>();
for (long i = 1; i <= N; i++) {
BigInteger integer = BigInteger.valueOf(i);
if (integer.isProbablePrime(1)) {
result.add((int) i);
}
}
result.forEach(System.out::println);
}
Updated 1:- that something you want
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
int[] result = new int[N];
int resultIncreamenter = 0;
// here for loop logic can be replaced with above 3 logic
for (int i = 1; i <= N; i++) {
boolean isPrime = true;
for (int j = 2; j < Math.sqrt(i - 1); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result[resultIncreamenter++] = i;
}
}
for (int j = 0; j < result.length; j++) {
System.out.print(result[j]);
if (j < result.length - 1) {
System.out.print(" ");
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
You lost the overview, though you have all functionality within reach.
public static boolean isPrime(int n) {
for (int i = 0; i < (n/2)+1; i++) {
if (n%i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
boolean printed = false;
for (int j = 2; j < N; j++) {
if (isPrime(j)) {
if (printed) {
System.out.print(" ");
}
System.out.print(j);
printed = true;
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
Simply use abstractions like isPrime.
Now for improvements (your results array): use the already found primes instead of all numbers in testing:
public static boolean isPrime(int n, int[] priorPrimes, int primesCount) {
for (int p : priorPrimes) {
if (n%p == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
int[] primes = new int[N];
int primesCount = 0;
boolean printed = false;
for (int j = 2; j < N; j++) {
if (isPrime(j)) {
primes[primesCount] = j;
++primesCount;
if (printed) {
System.out.print(" ");
}
System.out.print(j);
printed = true;
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
The algorithm using the Sieve of Eratosthenes taken from here:
private static int findNumberOfPrimes(int length) {
int numberOfPrimes = 1;
if (length == 2) {
return 1;
}
int[] arr = new int[length];
//creating an array of numbers less than 'length'
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
//starting with first prime number 2, all the numbers divisible by 2(and upcoming) is replaced with -1
for (int i = 2; i < arr.length && arr[i] != -1; i++) {
for (int j = i; j < arr.length; j++) {
if (arr[j] % arr[i] == 0) {
arr[j] = -1;
numberOfPrimes += 1;
}
}
}
return numberOfPrimes;
}
Update :
and this is how you list them :
package primelessthanN;
public class Main {
public static void main(String[] args) {
int j;
int n;
n = 10;
for (j = 2; j <=n; j++) {
if (isPrime(j))
System.out.println(j);
}
}
private static boolean isPrime(int m) {
for (int i = 2; i <= sqrt(m); i++) {
if (m % i == 0)
return false;
}
return true;
}
}

Check whether this matrix is symmetric in relation to the main diagonal

Given the number n, not exceeding 10, and a matrix of size n × n.
Check whether this matrix is symmetric in relation to the main diagonal. Output the word “YES”, if it is symmetric and the word “NO” otherwise.
This is my code, it unfortunately does not work. Please, explain to me how to do it correctly :)
public class Main { public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n= scanner.nextInt();
int[][] number = new int[n][n];
boolean ismatch = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
number[i][j] = scanner.nextInt();
}
}
int unevenchecker = (n% 2);
if (unevenchecker != 0) {
for (int k = 0; k < number.length - 1; k++) {
for (int l = 0; l < number.length - 1; l++) {
if (number[k][l] == number[l][k]) {
ismatch = true;
}
}
}
if (ismatch) {
System.out.print("YES");
}
} else {
System.out.print("NO");
}
}
}
The matrix is not symmetric if you find at least 1 symmetric couple where the 2 parts are not equal, so instead of checking for equality inside the loop, check for inequality:
ismatch = true;
for (int k = 0; k < number.length - 1; k++) {
for (int l = 0; l < number.length - 1; l++) {
if (number[k][l] != number[l][k]) {
ismatch = false;
break;
}
}
}
public class Main {
static boolean isSymmetric(int mat[][], int size) {
for (int i = 0; i < size; i++)
for (int j = i + 1; j < size - i; j++)
if (mat[i][j] != mat[j][i])
return false;
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n= scanner.nextInt();
int[][] number = new int[n][n];
boolean ismatch = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
number[i][j] = scanner.nextInt();
}
}
if (isSymmetric(number, n)) {
System.out.print("YES");
} else {
System.out.print("NO");
}
}
}
Notice that the nested loop into isSymmetric starts from j = i + 1, for not checking twice same condition.

Prime Numbers: What is wrong in my code? It works fine for till int limits as I go for long the code is taking a lot time

public class PrimeNumbers {
public static void main(String[] args) {
int i = 1000000000;
int m=2;
int n=1;
for (int j = 2; j < i; j++) {
int l=0;
if(j%25==0)
{
if(j%100==0)
{
m++;
}
if(j%1000==0)
{
m++;
}
m++;
}
if (j % 2 != 0) {
for (int k = 2; k < j/m; k++) {
if (j % k == 0) {
l++;
}
}
if (l < 1) {
n++;
}
if(n==1001)
{
System.out.print(j);
}
}
}
}
}
It works fine for numbers till ~100 million but as I'm going for larger numbers the result is inconsistent. I've seen the algorithms for prime numbers, just thought of trying.
int's are limited to represent numbers to approx. 2.1 billion. Past that the integer will begin to wrap around. Use the long data type instead and you will be able to go much higher.
I dont know what you are trying to do exactly, but what i judge you want to identify the prime numbers until the number you have specified... if this is what you need, here is the code:
public class PrimeNumbers {
public static void main(String[] args) {
int number = 20000;
int i = 1;
int j = 0;
while (i <= number) {
j = 1;
int counter = 0;
while (j <= i){
int divide = i / j;
if (i % j == 0){
counter++;
}
j++;
}
if (counter <= 2) {
System.out.print(i + " ");
}
i++;
}
}
}

Prime numbers calculator takes too much time (JAVA)

When I run this code to find sum of prime numbers below 20 it works fine, but when try to find sum below 2500000 it takes too much time. It's been at least 20 minutes and it's still running. It seems like it's not working. How do I fix it?
class PrimeSummation {
public static void main(String[] args) {
int sum = 0;
for(int i = 1; i < 2500000; i++) {
int count = 0;
for(int j = 1; j < i + 1; j++) {
if((i%j) == 0) {
count++;
}
}
if(count == 2) {
sum += i;
}
}
System.out.println(sum);
}
}
sum cannot be an int because the answer is 219697708195 whereas Integer.MAX_VALUE is only 2147483647. You must use a long or a BigInteger instead.
Your algorithm is very slow, because for every one of the 2500000 numbers you are starting from scratch to decide whether it is prime or not, and your approach for testing whether a number is prime (try every possible factor) is not very efficient.
The following code produces the answer in about a tenth of a second on my machine.
int num = 2500000;
long sum = 0;
boolean[] arr = new boolean[num];
for (int p = 2; p < num; p++) {
if (!arr[p]) {
sum += p;
for (int k = p * 2; k < num; k += p)
arr[k] = true;
}
}
System.out.println(sum);
Keeping track of previously found primes seems to help:
BigInteger sum = BigInteger.ZERO;
List<Integer> primes = new ArrayList<>();
for(int i = 2; i < 2500000; i++) {
boolean isPrime = true;
for(int j = 0; j < primes.size() && primes.get(j)<= Math.sqrt(i); j++) {
int p = primes.get(j);
if((i%p) == 0) {
isPrime=false;
break;
}
}
if(isPrime) {
sum = sum.add(BigInteger.valueOf(i));
primes.add(i);
}
}
System.out.println(sum);
Came up with answer:
219697708195
If you want better performance for generating a large number prime number, you should use Sieve formula.
You can Learn Sieve_of_Eratosthenes formula for prime number generation.
According to Sieve_of_Eratosthenes:
import java.util.*;
public class Sieve
{
private BitSet sieve;
private Sieve() {}
private Sieve(int size) {
sieve = new BitSet((size+1)/2);
}
private boolean is_composite(int k)
{
assert k >= 3 && (k % 2) == 1;
return sieve.get((k-3)/2);
}
private void set_composite(int k)
{
assert k >= 3 && (k % 2) == 1;
sieve.set((k-3)/2);
}
public static List<Integer> sieve_of_eratosthenes(int max)
{
Sieve sieve = new Sieve(max + 1); // +1 to include max itself
for (int i = 3; i*i <= max; i += 2) {
if (sieve.is_composite(i))
continue;
// We increment by 2*i to skip even multiples of i
for (int multiple_i = i*i; multiple_i <= max; multiple_i += 2*i)
sieve.set_composite(multiple_i);
}
List<Integer> primes = new ArrayList<Integer>();
primes.add(2);
for (int i = 3; i <= max; i += 2)
if (!sieve.is_composite(i))
primes.add(i);
return primes;
}
}
Performance:

Project Euler #23 in Java

I've spent quite a while working on Problem #23 on Project Euler.
The answer the program below gives me is 4190428, and I can't figure out why.
I think it's probably a one or two character mistake somewhere.
public long problem23() {
ArrayList<Integer> abundantNumbers = new ArrayList<Integer>();
int limit = 28123;
for(int i = 2; i < limit; i++) {
if(isAbundantNum(i)) {
abundantNumbers.add(i);
}
}
boolean [] abundantSum = new boolean [limit+1];
for(int a = 0; a < abundantNumbers.size(); a++) {
for(int b = 1; b < abundantNumbers.size(); b++) {
int temp = abundantNumbers.get(a) + abundantNumbers.get(b);
if(temp <= limit) {
abundantSum[temp] = true;
} else {
break;
}
}
}
long sum = 0;
for(int i = 1; i <= limit; i++) {
if(!abundantSum[i]) {
sum += i;
}
}
return sum;
}
public boolean isAbundantNum(int n) {
int factorSum = 1;
for(int i = 2; i < Math.sqrt(n); i++) {
if(n%i == 0) {
factorSum += i; factorSum += n/i;
}
}
if(factorSum > n) {
System.out.println(n);
return true;
}
return false;
}
Edit: Added isAbundantNum(int n) method.
You have 2 bugs...
for(int b = 1; b < abundantNumbers.size(); b++) {
'b' should start at zero not 1
for(int i = 2; i < Math.sqrt(n); i++) {
if(n%i == 0) {
factorSum += i; factorSum += n/i;
}
}
Factoring like that gives you duplicates (like 2*2 = 4, you're getting both 2s).
Try something like:
for(int i = 2; i < n; i++) {
if(n%i == 0) {
factorSum += i;
}
}
Here is another implementation:
import java.util.ArrayList;
import java.util.List;
public class P23 {
final static int MIN = 12;
final static int MAX = 28123;
static boolean numbers[] = new boolean[MAX+1];
static List<Integer> abundantNumbers = new ArrayList();
public static void main(String args[]) {
generateAbundants(MIN, MAX);
int size = abundantNumbers.size();
for (int i = 0; i < size; i++) {
for (int j = i; j < size; j++) {
int current = abundantNumbers.get(i) + abundantNumbers.get(j);
if (current <= MAX) {
numbers[current] = true;
} else {
break;
}
}
}
long sum = 0;
for (int i = 1 ; i <= MAX ; i++ ) {
if ( numbers[i] == false ) {
sum += i;
}
}
System.out.println(sum);
}
private static int sumOfProperDivisors(int x) {
int sum = 1;
int squareRoot = (int) Math.sqrt(x);
for (int i = 2; i <= squareRoot; i++) {
if (x % i == 0) {
sum += i;
sum += x / i;
}
}
// if x is a perfect square, it's square root was added twice
if (squareRoot * squareRoot == x) {
sum -= squareRoot;
}
return sum;
}
private static boolean isAbundant(int x) {
if (x < sumOfProperDivisors(x)) {
return true;
}
return false;
}
private static void generateAbundants(int min, int max) {
for (int i = min; i < max; i++) {
if (isAbundant(i)) {
abundantNumbers.add(i);
}
}
}
}
Time: 455 ms
Explanation:
The default value for j is i. You can take j = 0 ( as Ted Bigham said -> b in that case ), because it will work, but it will take into consideration every number twice ( 12+20 = 20+12 ). It's more efficient to start from i. Why isn't it good to start from 1? Because you can loose solutions: in my example 24 = 12 + 12.
Regarding the for loop containing the divisors part, you can use the approach containing sqrt because it's more efficient ( O(sqrt(n)) instead of O(n) ), but you have to adjust it. In my example you can see that I have <= squareRoot because if I don't use =, it will skip some values ( E.g.: 6 is divisor for 36, but you don't include it in your solution ). Because I counted 6 twice, I remove one of those roots. Of course that Ted's method is good, but sometimes it's better to have an improved performance, even if the simplicity is affected.

Categories