Print all prime numbers that are less than n - java

I wrote the following code:
package primelessthanN;
public class Main {
public static void main(String[] args) {
int j;
int n;
n = 10;
for (j = 3; j <=n; j++) {
if (isPrime(j))
System.out.println(j);
}
}
private static boolean isPrime(int m) {
for (int i = 3; i <=m; i++) {
if (m % i == 0)
return false;
}
return true;
}
}
I do not know why it doesn't work and I am a little bit nervous.
Could any of you help me please and tell me where it is my mistake?

There are two problems:
In main you iterate from 3 to sqrt(n), but you have to start from 2 (which is a prime) and iterate to n
for (j = 2; j <=n; j++) {
if (isPrime(j)) {
System.out.println(j);
}
}
In isPrime you have to start the iteration from 2 since it is a prime number too.
for (int i = 2; i <= sqrt(m); i++) {
if (m % i == 0)
return false;
}
return true;

Related

how to find the sum of all the prime numbers between 1 and 50 in java?

i have the following code, but the answer is coming out to be 2.
public class Main {
public static void main(String[] args) {
int sum = 0;
int count = 0;
for(int i = 2; i <= 50; i++) {
for(int j = 1; j <= i; j++) {
System.out.println(j);
if(i % j == 0) {
count++;
}
if(count == 2) {
System.out.println(i);
sum = sum + i;
}
}
}
System.out.println("The sum: " + sum);
}
}
You were close. But here is all you need.
first, set sum to 2. It is the only even prime and doing this allows a better increment below
now increment the test cases starting at 3 and incrementing by 2. Skip even values.
now divide by each test case by numbers from 2 to the sqrt(i). No need to go beyond that.
as soon as you have a successful division, end the inner loop and start the next of the outer loop.
otherwise, if the inner loop completes, add i to sum.
int sum = 2;
outer:
for(int i = 3; i <= 50; i+= 2) {
for(int j = 2; j <= Math.sqrt(i); j++) {
if(i % j == 0) {
continue outer;
}
}
sum += i;
}
System.out.println("The sum: " + sum);
An improvement would be to store the primes as they are found and then only divide by those instead of arbitrary numbers.
Disclaimer: this code was written by Github Copilot with minimal supervision.
class Scratch {
// find the sum of all prime numbers between 2 and n
public static int sumPrimes(int n) {
int sum = 0;
for (int i = 2; i < n; i++) {
if (isPrime(i)) {
sum += i;
}
}
return sum;
}
// return true if n is prime
public static boolean isPrime(int n) {
if (n == 2) {
return true;
}
if (n % 2 == 0) {
return false;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
// print sum of primes between 2 and 50
System.out.println("The sum: " + sumPrimes(50));
}
}
Prints:
The sum: 328
Maybe a minimal version with recursive method based on Aivean response:
class Scratch {
// find the sum of all prime numbers between 2 and n
public static int sumPrimes(int n) {
if (n >= 2) {
return (isPrime(n) ? n : 0) + sumPrimes(n-1);
}
return 0;
}
// return true if n is prime
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
// print sum of primes between 2 and 50
System.out.println("The sum: " + sumPrimes(50));
}
}

Project Euler #3 Java: Why count up to square root when finding the largest prime factor, rather than counting down from square root?

I'm trying to solve problem 3 of project Euler and I have written the following code which gives me the correct answer
public class LargestPrimeFactor {
public static boolean isPrime(int p) {
boolean isPrime = true;
for (int i = 2; i < p / 2; i++) {
if (p % i == 0) {
return false;
}
}
return isPrime;
}
public static double largestPrimeFactor(long n) {
double factor = 0;
for (int j=1; j<Math.sqrt(n); j++) {
System.out.println("j is : "+ j);
if (n % j == 0 && isPrime(j)) {
factor = j;
}
}
return factor;
}
public static void main(String args[]) {
long limit = 600851475143L;
System.out.println(largestPrimeFactor(limit));
}}
I was wondering wether it is a good idea to start at 1 and increase towards the square root, when we are looking for the largest factor. So I tried to change the for loop in the largestPrimeFactor(long n) method to start from the square root of n and count down. However now I get an incorrect answer. What is the reason for this?
public class LargestPrimeFactor {
public static boolean isPrime(int p) {
boolean isPrime = true;
for (int i = 2; i < p / 2; i++) {
if (p % i == 0) {
return false;
}
}
return isPrime;
}
public static double largestPrimeFactor(long n) {
double factor = 0;
for (int j=(int)Math.sqrt(n); 1<j; j--) {
System.out.println("j is : "+ j);
if (n % j == 0 && isPrime(j)) {
factor = j;
}
}
return factor;
}
public static void main(String args[]) {
long limit = 600851475143L;
System.out.println(largestPrimeFactor(limit));
}}
You don't have a break after finding the first prime factor - the first you find is the largest and you shouldn't search any further. For that you should return the first correct value you find like this
public static double largestPrimeFactor(long n) {
double factor = 0;
for (int j=(int)Math.sqrt(n); 1<j; j--) {
if (n % j == 0 && isPrime(j)) {
return j; // Changed this line
}
}
return factor;
}

Getting the first 100 prime numbers in an array

Hey so im trying to create a program that prints out the first 100 prime numbers. this is my code however it doesn't print out the first hundred but the primes from 2 to 100. what am i doing wrong here that make it print out only those ant not the first hundred?
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
public class Prime {
public static void main(String[] args) {
int maxCount = 100;
int[] values = new int[maxCount];
int temp = 3;
boolean prime = true;
for (int j = 1; j < maxCount; ++j) {
values[j] = j + 1;
if (values[j] == 2) {
System.out.println(values[j]);
}
}
for (int j = 2; j < maxCount; ++j) {
if (values[j] % 2 == 0)
prime = false;
else {
boolean prime2 = true;
double test = Math.sqrt(values[j]);
int divisor = 3;
while (prime2 && (divisor <= test)) {
if (values[j] % divisor == 0) {
prime2 = false;
} else divisor += 2;
}
if (prime2)
System.out.println(values[j]);
}
}
}
}
You're looping until j < maxCount while you should loop until the number of elements in the array are equal to maxCount. For that you'll need another counter which is val_cnt in the following fixed code.
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
public class Prime {
public static void main(String[] args) {
int maxCount = 100;
int[] values = new int[maxCount];
int temp = 3;
int val_cnt = 0;
values[val_cnt++] = 2;
System.out.println(2);
for (int j = 3; val_cnt < maxCount; ++j) {
boolean prime = true;
if (j % 2 == 0)
prime = false;
else {
double test = Math.sqrt(j);
int divisor = 3;
while (prime && (divisor <= test)) {
if (j % divisor == 0) {
prime = false;
} else divisor += 2;
}
if (prime) {
values[val_cnt++] = j;
System.out.println(j);
}
}
}
}
}
you are making your loop iterate till j becomes 100 , and at every iteration irrespective of whether a prime number has been found or not, j gets incremented.
So have something like:-
while(maxCount<100){
if(number_is_prime){
increment maxCount;
}
else{
continue;
}
You are iterating your loop till 100 only. But you want to print first 100 prime numbers, not prime numbers between 1 to 100. so every time the number is found to be a prime number just increment the count(which counts the number of prime numbers printed.) to 1 and exit from the loops when the count is 100.Here is the simple approach for printing first 100 prime numbers:
int count = 0,flag=0;
for(int i=2;count<100;i++){
flag = 0;
for(int j=2;j<i;j++){
if(i%j == 0){
flag ++;
break;
}
}
if(flag == 0){
System.out.println(i);
count++;
}
}
Only increase the value of j if prime number is found,
Re-format your codes same as this,
for (int j = 2; j < maxCount;) {
if (values[j] % 2 == 0){
prime = false;
j++;
}
else {
boolean prime2 = true;
double test = Math.sqrt(values[j]);
int divisor = 3;
while (prime2 && (divisor <= test)) {
if (values[j] % divisor == 0) {
prime2 = false;
} else divisor += 2;
}
if (prime2)
System.out.println(values[j]);
j++;
}
Try this
class PrimeNumbers {
public static void main (String[] args) {
int i =0; int num =0;
String primeNumbers = "";
for (i = 1; i <= 100; i++) {
int counter=0;
for(num =i; num>=1; num--) {
if(i%num==0) {
counter = counter + 1;
}
}
if (counter ==2) {
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to 100 are :");
System.out.println(primeNumbers);
}
}

Prime Number in java

I wrote some code to find prime numbers up to a given number. Could you guys let me know ways to make my code more efficient or better? Or give insight on how I did? In addition, there is a problem in my code where certain numbers repeats twice or three times in a pattern. How do I fix this?
public class PrimeNumber2 {
public static void main(String[] args)
{
int max_prime = 10000;
for(int i = 3; i < max_prime; i+=2)
{
for(int j = 1; j < Math.sqrt(i); j++)
{
if(i % j == 0)
{
System.out.println(i);
}
}
}
}
}
Have a look at:
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
This is quite a nice way of doing it.
Here is some code for you to look at:
public void runEratosthenesSieve(int upperBound) {
int upperBoundSquareRoot = (int) Math.sqrt(upperBound);
boolean[] isComposite = new boolean[upperBound + 1];
for (int m = 2; m <= upperBoundSquareRoot; m++) {
if (!isComposite[m]) {
System.out.print(m + " ");
for (int k = m * m; k <= upperBound; k += m)
isComposite[k] = true;
}
}
for (int m = upperBoundSquareRoot; m <= upperBound; m++) {
if (!isComposite[m]) {
System.out.print(m + " ");
}
}
Here´s a tuned version of yours.
I did put the check if the number is prime into a seperate method. That´s also a part of the reason why your version did print values multiple times, since if it found out that it has a divisor, then it would print the values. (Also you´r algorythm would print basicly everything despite it beeing prime or not, for example it prints 15 and 27).
The reason why it did print multiple values was, that once you found a divisor it would have printed i, but it would continue looping. If it would have found another divisor, it would print i again(you can notice that it does not only print prime numbers).
Here is the fixed version of your´s
public static void main(String[] args) {
if(isPrime(2)) {
System.out.println(2);
}
int max_prime = 10000;
for(int i = 3; i < max_prime; i+=2)
{
if(isPrime(i)) {
System.out.println(i);
}
}
}
private static boolean isPrime(int n) {
if(n<=1) return false;
if(n == 2) return true;
for(int i = 2;i*i<=n;++i) {
if(n%i == 0) return false;
}
return true;
}
Try this.
public class PrimeNumber2 {
public static void main(String[] args)
{
int max_prime = 10000;
System.out.println(2);
L: for (int i = 3; i < max_prime; i += 2)
{
for (int j = 3, max = (int)Math.sqrt(i); j <= max ; j += 2)
{
if(i % j == 0)
{
continue L;
}
}
System.out.println(i);
}
}
}
Here a way using parallelStream
System.out.println(2);
IntStream.range(1, 10000000)
.map(i -> i * 2 + 1)
.filter(i -> (i & 1) != 0 && IntStream.range(1, (int) (Math.sqrt(i)-1)/2)
.map(j -> j * 2 + 1)
.noneMatching(j -> i % j == 0)
.forEach(System.out::println);
Note: the ranges test the n-th odd number.
public static void main(String[] args) {
int upperBound = 30;
List<Integer> primes = new ArrayList<>();
// loop through the numbers one by one
for (int number = 2; number < upperBound; number++) {
boolean isPrimeNumber = true;
// check to see if the number is prime
for (int j = 2; j < number; j++) {
if (number % j == 0) {
isPrimeNumber = false;
break; // exit the inner for loop
}
}
// print the number if prime
if (isPrimeNumber) {
primes.add(number);
}
}
System.out.println("The number of prime is: " + primes.size() + ", and they are: " + primes.toString());
}
possible to dupplicate
get prime numbers and total prime numbers in range
public boolean isPrimeNumber(int number) {
for (int i=2; i<=number/2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}

Prime Numbers III Problem 18 - I dont get the right answer even though I think I am right

I am new here. I am trying to solve this exercise Problem 18 just for reinforcing my solving skills. I've already coded the answer. The task asks for "How many of the primes below 1,000,000 have the sum of their digits equal to the number of days in a fortnight?" (a fortnight is 14 days). My answers is 16708, but it is wrong. I hope you can help me. I don't know what my error is. I have 2 methods, 1 for generating the primes, and another for counting the digits of each prime.
This is my code:
import java.util.ArrayList;
import java.util.List;
public class Problema18 {
public static void main(String args[]) {
ArrayList<Integer> num = primes();
System.out.println(num);
count(primes());
}
public static ArrayList<Integer> primes() {
List<Integer> primes = new ArrayList<Integer>();
primes.add(2);
for (int i = 3; i <= 1000000; i += 2) {
boolean isPrime = true;
int stoppingPoint = (int) (Math.pow(i, 0.5) + 1);
for (int p : primes) {
if (i % p == 0) {
isPrime = false;
break;
}
if (p > stoppingPoint) { break; }
}
if (isPrime) { primes.add(i); }
}
// System.out.println(primes);
return (ArrayList<Integer>) primes;
//System.out.println(primes.size());
}
public static void count(ArrayList<Integer> num) {
int count = 0;
for (int i = 0; i <= num.size() - 1; i++) {
int number = num.get(i);
String num1 = String.valueOf(number);
int sum = 0;
for (int j = 0; j < num1.length(); j++) {
sum = Integer.parseInt(num1.charAt(j) + "") + sum;
if (sum == 14) { count++; }
}
System.out.println(sum);
}
System.out.println(count);
}
}
You should check whether sum == 14 outside the inner for loop. What happens now is that you also count those primes for which the sum of digits is larger than 14 but the sum of the digits in some prefix of the prime is equal to 14.
This part...
if (sum == 14) {
count++;
}
should be outside the inner for-loop - i.e. you want to do it each time you pass through the i for-loop, but not each time you pass through the j for-loop.
Like this:
public static void count(ArrayList<Integer> num) {
int count = 0;
for (int i = 0; i <= num.size() - 1; i++) {
int number = num.get(i);
String num1 = String.valueOf(number);
int sum = 0;
for (int j = 0; j < num1.length(); j++) {
sum = Integer.parseInt(num1.charAt(j) + "") + sum;
}
System.out.println(sum);
if (sum == 14) {
count++;
}
}
System.out.println(count);
}

Categories

Resources