listing prime numbers from user input in java - java

in java what i am trying to do is have a user input a value greater than 0 and with that number they input list that amount of prime numbers starting from 2
so if the user inputs "3" the program will display 2,3,5
if the user inputs "5" the program will display 2,3,5,7,11
and so on
the problem is I cant figure out how to have the user input do this correctly, i either end up with the numbers repeating however many times or the list ending at the user input, any help would be apreciated
import java.util.Scanner;
public class Primes
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int n = console.nextInt();
if(n<=0)
{
return;
}
else
{
for(int i=2; i < 100; i++)
{
boolean isPrime = true;
for(int j=2; j < i; j++)
{
if(i%j == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
System.out.println(i);
}
}
}
}
}

Keep a count of how many primes have been found by changing your for loop to stop when you've found enough primes and performing primesFound++ when a prime is found:
for (int i = 2, primesFound = 0; primesFound < n; i++)
{
boolean isPrime = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
System.out.println(i);
primesFound++;
}
}

I rather have code that is refactored, each method is doing one thing, it makes it much easier to read, debug and maintain.
All we need to do is separate the logic that checks if a number is prime from the logic that goes over the numbers until n prime numbers are found:
public static void main(String[] args) {
printNPrimes(5);
}
static private boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
static private void printNPrimes(int n) {
int i = 2;
while (n > 0) {
if (isPrime(i)) {
System.out.println(i + " is Prime");
n--;
}
i++;
}
}

//prime
int i,j;
Set<Integer> primeNums = new HashSet<>();
Set<Integer> notPrimeNums = new HashSet<>();
Stack<Integer> stack = new Stack<>();
for(i=1; i<fiboList.size(); i++) {
for(j=i+1; j<fiboList.size(); j++) {
if( i % j == 0 ) {
notPrimeNums.add(fiboList.get(i));
}else {
primeNums.add(fiboList.get(i));
}
}
}
stack.addAll(primeNums);
Collections.sort(stack);
System.out.println("Prime numbers:"+" "+stack);
}

Related

How would I get this for loop to print prime numbers only?

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);
}
}
}

Program to find the last three prime number lesser than 100

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--;
}

Java code for project euler #7 gives wrong answer [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This code is meant to find the 1001st prime but gives me the answer 47 which is clearly wrong.
public class problem7 {
public static void main(String[] args) {
int[] myarray = new int[1001];
int j = 0;
boolean prime = false;
for (int i = 2;; i++) {
for (int k = 2; k < i; k++) {
if (i == (k - 1) && i % k != 0) {
prime = true;
}
if (i % k == 0) {
prime = false;
prime = true;
}
if (prime) {
myarray[j] = i;
}
if (j == 1000) {
System.out.println(myarray[1000]);
return;
}
j++;
}
}
}
}
Any help would be greatly appreciated.
Your check for prime is wrong: you cannot declare a number prime and set prime = true based on a single test. The inner loop should set prime to false, but it shouldn't reset it to true: once it's false, it's false.
The algorithm should proceed as follows:
For each i, set prime=true
Loop over potential divisors k
If a divisor such that i % k == 0 is found, set prime = false, and break the loop
If prime is still true at the end of the nested loop, add i to the list of primes.
This should give you a correct result, at which point you should consider optimizing your solution using considerations below:
If you did not find a divisor among k below or at sqrt(i), then i is prime
You do not have to try all numbers k, only the ones from the list of primes that you have discovered so far.
I think j++ is increment only if prime number is inserted not at all case.By using this code you will be get your 1001 Prime number
public static void main(String[] args) {
int[] myarray = new int[1001];
int j = 0;
for (int i = 2;; i++) {
boolean prime = false;
for (int k = 2; k < i; k++) {
if (i % k == 0) {
prime = true;
}
}
if (!prime) {
myarray[j] = i;
j++;
}
if (j == 1001) {
break;
}
}
for (int primeNumber : myarray) {
System.out.println(primeNumber);
}
}
This is an implementation of dasblinkenlights algorithm!
public static void main(String args[]) {
int[] primes = new int[1001];
int i = 1;
int index = 0;
while (primes[1000] == 0) {
i++;
boolean skip = false;
for (int i1 : primes) {
if (i1 == 0)
break;
if (i % i1 == 0) { //checks if the number is a multiple of previous primes, if it is then it skips it
skip = true;
break;
}
}
if (!skip) {
if (isPrime(i)) {
primes[index] = i;
System.out.println(i);
index++;
}
}
}
}
static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true;
}
The primality test you done here is kind of ambiguous. Because the general approach is, we pick any number assuming its prime, so at the beginning, prime = true. Then if there exist any factor k of input such that k < input and kthen the number is not prime, so prime = false.
I modified your code and get a result: 104743 .
Update: Here is a bit faster way to find large prime. The inner loop will iterate up to square root of i, reason: Why do we check upto the square root of a prime number to determine if it is prime?
public static void main(String[] args) {
int[] myarray = new int[10001];
int j = 0;
boolean prime = true;
int i = 2;
while (true) {
prime = true;
for (int k = 2; k*k <= i; k ++) {
if (i % k == 0) {
prime = false;
}
}
if (prime) {
myarray[j] = i;
if (j == 10000) {
System.out.println(myarray[10000]);
return;
}
j++;
}
if(i > 4)
i += 2;
else
i++;
}
}

How to make a newline for every 15 spaces with numbers in java

I have the following code that finds the prime factors from 1 to the user input. The problem is that the output is in one very long line, I want every 15 numbers to output then go to the next line. How would I do that?
Here is my code:
public static void main (String args[])
{
System.out.println("\nLab1la\n");
Scanner input = new Scanner(System.in);
System.out.println("Enter the primes upperbond ==>> ");
final int MAX = input.nextInt();
input.nextLine();
boolean primes[];
primes = new boolean[MAX];
ArrayList<Integer>PrimeFactor = new ArrayList<Integer>();
for (int i = 2; i < MAX + 1 ; i++)
{
PrimeFactor.add(i);
}
System.out.println("COMPUTING RIME NUMBERS");
System.out.println();
System.out.println("PRIMES BETWEEN 1 AND " + MAX);
CompositeNumbers(PrimeFactor);
for (int value : PrimeFactor)
{
System.out.print(value);
System.out.print(" ");
}
}
public static void CompositeNumbers(ArrayList<Integer> PrimeFactor)
{
for (int i = 0; i < PrimeFactor.size(); i++)
{
if (!isPrime(PrimeFactor.get(i)))
{
PrimeFactor.remove(i);
i--;
}
}
}
public static boolean isPrime(int n)
{
if(n==1)
{
return true;
}
for (int i = 2; i < n +1/2; i++)
{
if (n%i == 0)
{
return false;
}
}
return true;
}
}
You could do something like this:
for (int i = 0; i < PrimeFactor.size(); i++)
{
if (i > 0 && i % 15 == 0) System.out.println();
System.out.print(PrimeFactor.get(i));
System.out.print(" ");
}
You could just have a counter and take a mod of this counter value for 15 and print it in the next line, like below. Like #soong described
int counter = 0;
for (int value : PrimeFactor)
{
if(counter % 15 == 0){
System.out.println();
}
System.out.print(value);
System.out.print(" ");
counter++;
}

Largest prime factor program takes aaaages - Java

So this is problem 3 from project Euler. For those who don't know, I have to find out the largest prime factor of 600851475143. I have the below code:
import java.lang.Math;
// 600851475143
public class LargestPrimeFactor {
public static void main(String[] stuff) {
long num = getLong("What number do you want to analyse? ");
long[] primes = primeGenerator(num);
long result = 0;
for(int i = 0; i < primes.length; i++) {
boolean modulo2 = num % primes[i] == 0;
if(modulo2) {
result = primes[i];
}
}
System.out.println(result);
}
public static long[] primeGenerator(long limit) {
int aindex = 0;
long[] ps = new long[primeCount(limit)];
for(long i = 2; i < limit + 1; i++) {
if(primeCheck(i)) {
ps[aindex] = i;
aindex++;
}
}
return ps;
}
public static boolean primeCheck(long num) {
boolean r = false;
if(num == 2 || num == 3) {
return true;
}
else if(num == 1) {
return false;
}
for(long i = 2; i < Math.sqrt(num); i++) {
boolean modulo = num % i == 0;
if(modulo) {
r = false;
break;
}
else if(Math.sqrt(num) < i + 1 && !modulo) {
r = true;
break;
}
}
return r;
}
public static int primeCount(long limit) {
int count = 0;
if(limit == 1 || limit == 2) {
return 0;
}
for(long i = 2; i <= limit; i++) {
if(primeCheck(i)) {
count++;
}
}
return count;
}
public static long getLong(String prompt) {
System.out.print(prompt + " ");
long mrlong = input.nextLong();
input.nextLine();
return mrlong;
}
}
But when I test the program with something (a lot) smaller than 600851475143, like 100000000, then the program takes its time - in fact, 100000000 has taken 20 minutes so far and is still going. I've obviously got the wrong approach here (and yes, the program does work, I tried it out with smaller numbers). Can anyone suggest a less exhaustive way?
public static void main(String[] args) {
long number = 600851475143L;
long highestPrime = -1;
for (long i = 2; i <= number; ++i) {
if (number % i == 0) {
highestPrime = i;
number /= i;
--i;
}
}
System.out.println(highestPrime);
}
public class LargestPrimeFactor {
public static boolean isPrime(long num){
int count = 0;
for(long i = 1; i<=num/2 ; i++){
if(num % i==0){
count++;
}
}
if(count==1){
return true;
}
return false;
}
public static String largestPrimeFactor(long num){
String factor = "none";
for(long i = 2; i<= num/2 ; i++){
if(num % i==0 && isPrime(i)){
factor = Long.toString(i);
}
}
return factor;
}
public static void main(String[] args) {
System.out.println(largestPrimeFactor(13195));
}
}
I have done several dozen of the challenges on Project Euler. Some of the questions can be solved with brute force (they recommend not to do this) but others require "out of the box" thinking. You cannot solve that by problem with brute force.
There is lots of help on the web to lead you in the right direction, for example:
http://thetaoishere.blogspot.com.au/2008/05/largest-prime-factor-of-number.html
The number of prime factors a number can have is always less than sqrt of that number so that there is no need to iterate through the number n to find its largest prime factor.
See this code.
public class LargestPrimeFactor {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long num=sc.nextLong();
if(num>0 && num<=2)
{
System.out.println("largest prime is:-" + num);
System.exit(0);
}
int i=((Double)Math.sqrt(num)).intValue();
int j=3;
int x=0;
//used for looping through the j value which can also be a prime. for e.g in case of 100 we might get 9 as a divisor. we need to make sure divisor is also a prime number.
int z=0;
//same function as j but for divisor
int y=3;
int max=2;
//divisor is divisible
boolean flag=false;
//we found prime factors
boolean found=false;
while(x<=i)
{
y=3;
flag=false;
if(num % j ==0)
{
if(j>max)
{
for(z=0;z<Math.sqrt(j);z++)
{
if(j!=y && j % y==0)
{
flag=true;
}
y+=2;
}
if(!flag)
{
found=true;
max=j;
}
}
}
j+=2;
x++;
}
if(found){
System.out.println("The maximum prime is :- " + max);
}
else
{
System.out.println("The maximum prime is :- " + num);
}
}
}
change
for(long i = 2; i <= limit; i++)
to
// add the one for rounding errors in the sqrt function
new_limit = sqrt(limit) + 1;
// all even numbers are not prime
for(long i = 3; i <= new_limit; i+=2)
{
...
}
Factoring 1,000,000 for example instead of iterating 1,000,000 times
the thing only needs to do around 500 iterations.

Categories