I have been working on some java code to show prime numbers . I have got as far as having it show all prime numbers between 0 and 100 .
How would I make it so that I could set a variable to say 20 and it would show me the first 20 prime numbers.
My Code :
public class PrimeNumber {
/**
* #param args the command line arguments
*/
private static boolean prime = true;
private static int count = 20;
public static void main(String[] args) {
for (int i = 2; i < 100; i++) {
for (int j = 2; j < 100; j++) {
if(i == j)
{
continue;
}
if (i % j == 0) {
prime = false;
break;
} else {
prime = true;
}
}
if (prime) {
System.out.println(i + " is a Prime:");
}
}
}
}
Here is the simplest possible implementation, for the OPs code.
Decrease the count variable and check it in the outer for loop till it reaches zero. Also Inner for-loop should check only till the current value of (i/2 + 1). The other half you can always skip, the value will will divide the number will be i itself.
public class PrimeNumber {
/**
* #param args the command line arguments
*/
private static boolean prime = true;
private static int count = 20;
public static void main(String[] args) {
for (int i = 2; count>0; i++) {
for (int j = 2; j < i/2 + 1; j++) {
if (i % j == 0) {
prime = false;
break;
} else {
prime = true;
}
}
if (prime) {
System.out.println(i + " is a Prime:");
count--;
}
}
}
}
Check below code for your answer:
public class PrimeNumber {
private static boolean prime = true;
private static int count = 20;
public static void main(String[] args) {
for (int i = 2; i < count+1; i++) {
for (int j = 2; j < 100; j++) {
if(i == j)
{
continue;
}
if (i % j == 0) {
prime = false;
break;
} else {
prime = true;
}
}
if (prime) {
System.out.println(i + " is a Prime:");
}}}}
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);
}
}
}
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);
}
public class PalindromicPrimes {
public static void main (String[] args) {
userInt();
System.out.println("The palindromic primes less than " + userInt() +
" are:");
for (int i = 0; i <= userInt(); i++) {
if (isPrime() && isPalindrome()) {
System.out.println(i);
}
}
}
private static boolean isPrime() {
if (userInt() == 2 || userInt() == 3) {
return true;
}
if (userInt() % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(userInt()) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (userInt() % i == 0) {
return false;
}
}
return true;
}
private static boolean isPalindrome() {
if (userInt() < 0)
return false;
int div = 1;
while (userInt() / div >= 10) {
div *= 10;
}
while (userInt() != 0) {
int x = userInt();
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
private static int userInt() {
Scanner s = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int userInt = s.nextInt();
return userInt;
}
}
is there a different way of getting the user input? or can I keep it this way?
when it runs it just keeps prompting the user input.
rearrange it like this:
public static void main (String[] args) {
//get it and save it here!
int userValue = userInt();
System.out.println("The palindromic primes less than " + userValue +
" are:");
for (int i = 0; i <= userValue; i++) {
if (isPrime(userValue) && isPalindrome(userValue)) {
System.out.println(i);
}
}
}
then also update all the methods that care about this "userInt" value.
Every time you call userInt() you're telling the code to get a new value from the command line.
Try this:
public static void main (String[] args) {
int value = userInt();
System.out.println("The palindromic primes less than " + value +
" are:");
for (int i = 0; i <= value; i++) {
if (isPrime() && isPalindrome()) {
System.out.println(i);
}
}
}
The term userInt() is a function invocation that prompts the user for input. Odds are you only want to do this once. You're doing it multiple times.
You should store the result of userInt() in a variable.
int typed = userInt();
And then use this variable to reference what the user typed instead of calling userInt() again.
System.out.println("The palindromic primes less than " + typed +
" are:");
for(int i = 0; i < typed; i++) ...
You keep calling userInt(). That is the problem.
I don't understand your logic. So I have not modified that code. But the code runs.
import java.util.Scanner;
public class PalindromicPrimes {
public static void main (String[] args) {
int x = userInt();
System.out.println("The palindromic primes less than " + x +
" are:");
for (int i = 0; i <= x; i++) {
if (isPrime(i) && isPalindrome(i)) {
System.out.println(i);
}
}
}
private static boolean isPrime(int a) {
if (a == 2 || a == 3) {
return true;
}
if (a % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(a) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (a % i == 0) {
return false;
}
}
return true;
}
private static boolean isPalindrome(int a) {
if (a < 0)
return false;
int div = 1;
while (a / div >= 10) {
div *= 10;
}
while (a != 0) {
int x = a;
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
private static int userInt() {
Scanner s = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int userInteger = s.nextInt();
return userInteger;
}
}
Remember, don't use the same names for variable and function. In the function userInt(), you have used a variable int userInt, to get the result from the scanner. This might be aa recursive call sometimes. Be careful with that.
public String primeNumbers()
{
//create variable to be returned
String prime = "";
int num = 0;
for(int i = 0; i < this.limit; i++)
{
num = this.limit - i;
for(int count = 2; count < this.limit; count++)
{
if ( num % count == 0)
{
count = this.limit + 1;
}
else if ( num == count)
{
prime += num + ", ";
}
}
}
return prime;
}
The goal of this is to produce a list of prime numbers in between 1 and the upper limit which is the private variable limit. However, when I run the code, I get a blank message as a return. Why is this?
I don't quite understand the logic of your code, but having helper methods is good.
public String primeNumbers()
{
//create variable to be returned
String prime = "";
for(int i = 0; i < this.limit; i++)
{
if(this.isPrime(i)){
prime += i + ", ";
}
}
return prime;
}
private boolean isPrime(int number){
if(number <= 1){
return false;
} else if(number == 2){
return true;
}
for(int i = 2; i < number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
The isPrime() is naive, and can definitely be optimized.
There was a question about this yesterday and I ended up writing this as a refresher for myself.
public class Erasthotenes
{
private int range;
private boolean[] nums;
public Erasthotenes(int range)
{
this.range = range;
nums = new boolean[range];
for(int i = 0; i < nums.length; ++i)
{
nums[i] = true;
}
nums[0] = nums[1] = false;
}
public void sieve()
{
int root = (int) Math.sqrt(range);
for(int i = 2; i < root; ++i)
{
for(int j = i + 1; j < range; ++j)
{
if(j % i == 0)
{
nums[j] = false;
}
}
}
}
public void printPrimes()
{
for(int i = 0; i < nums.length; ++i)
{
if(nums[i] == true)
{
System.out.print(i + ", ");
}
}
}
}
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
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.