Display Prime numbers with MVC Java - java

I have a Prime class which extends JFrame and it has a simple JSpinner for displaying prime numbers.
I want to create a Model for displaying prime numbers infinitely (until long ends). Here is the model class I have written:
public class PrimeSpinnerModel extends AbstractSpinnerModel{
long current;
public PrimeSpinnerModel() {
this.current = 2;
}
#Override
public Object getValue() {
return current;
}
#Override
public Object getNextValue() {
long newLatest = current + 1;
if(isPrime(newLatest)){
current = newLatest;
}else{
System.out.println(newLatest + "no prime");
newLatest ++;
current = newLatest;
}
fireStateChanged();
return getValue();
}
#Override
public Object getPreviousValue() {
fireStateChanged();
return getValue(); // without this the component wouldn't know to update.
}
#Override
public void setValue(Object value) {
throw new IllegalArgumentException("Static spinner model Prime does not support editing.");
}
static boolean isPrime(long n) {
if (n == 1) return false;
for(long i = 2; i <= n/2; i++)
if(n % i == 0)
return false;
return true;
}
}
When I run the code, it displays prime numbers as 2,3,5,7,9,11,13 etc.
Why 9 is displayed?

Suppose current is 7 when getNextValue() is invoked. Then newLatest is set to 8. isPrime(8) is obviously false, so then you increment newLatest, making it 9. You assign it to current and return it. This makes 9 the next number after seven, regardless of whether it is prime or not.
To solve this, you should increment newLatest while it is not prime (in a loop). That way, you ensure you continue until you found a prime number. See below:
newLatest = current + 1;
while (!isPrime(newLatest)) {
newLatest++;
}
// newLatest now contains the new prime number.
current = newLatest;
// etc..

Try this :)
public static void showPrimeNumbers(int n){
for (int i=2; i<n; i++){
boolean istrue = true;
for (int x=2; x<i; x++){
if (i%x==0){
istrue = false;
}
}
if (istrue==true){
System.out.println(i);
}
}
}

Related

Is there a way to return void in int type method

I was trying to create a method to check if a number is a prime or not but while creating the method I am getting 0 instead of void. Is there a way to skip where I am getting 0 with void. If not,suggest any other way please.
I tried int replacing a with null but casting from null to int is not possible
public int getPrime(int n) {
int a =0;
boolean k = true;
for (int i = 2 ; i<n;i++) {
if(n%i==0) k = false;
}
if(k==true) { a = n;
return a;}
else {return null;} //Here is the problem
Use non-primitive types here. Integer vs int. That will allow you to return null where needed.
I think you are trying to check if your number is primary or not, the method must return boolean not int.
public boolean isPrime(int n) {
for (int i = 2 ; i<n;i++) {
if(n%i==0) return false;
}
return true;
}
It is not the most optimal algorithm, but it works with true types.
Yes-no prime check with boolean result:
public static boolean isPrime(int n) {
if(n<2)
return false;
for(int i=(int)Math.sqrt(n); i>=2; i--)
if(n%i == 0)return false;
return true;
}
Print primes, do not print non-primes:
public static void main(String args[]) {
for(int i=0;i<100;i++)
if(isPrime(i))
System.out.println(i);
}
Test: https://ideone.com/nNiY1T

What's the logical flaw in my iteration method?

When iterate() is first called i'm generating a random number between 1-1024 and then checking if that random number is equal to 1. If it is, then done = true and the return value should be 10. If it's not, then the value of x should be decremented (x now = 9). I then expect getRandNum() to be called again within iterate(), this time generating a random number between 1-512 and checking if it's equal to 1 etc, etc... until the return value for x can only be equal to 1.
import java.util.Random;
public class Main {
static boolean done = false;
public static int rand(int x) {
Random rand = new Random();
return rand.nextInt(x) + 1;
}
public static int value(int x) {
return (int) Math.pow(2, x);
}
public static int getRandNum(int x) {
return rand(value(x));
}
public static int iterate() {
int x = 10;
do {
if (getRandNum(x) == 1) {
done = true;
}
else {
if (x > 1) {
x--;
}
else {
x = 1;
done = true;
}
}
} while (done = false);
return x;
}
public static void main(String[] args) {
System.out.println(iterate());
}
}
Right now iterate() only returns 9. I need it to return anything from 1-10. There's clearly a logical error, but i can't see it.
Small error: you did while(done = false). This assigns done to false. The correct way to do this is while(!done).
public static int iterate() {
int x = 10;
do {
if (getRandNum(x) == 1) {
done = true;
}
else {
if (x > 1) {
x--;
}
else {
x = 1;
done = true;
}
}
} while (!done);
return x;
}
If you do this it prints 1.

How do I make this output a boolean?

So here's my code, I want the output to be like this:
Given two numbers, is the second input a multiple of the first?
For Example:
Input:
3
6
Output:
true
public boolean multiple(int m, int n){
int i = 0;
int j = 0;
boolean check = true;
if(n%m == 0){
i++;
return check;
}
else{
j++;
return false;
}
}
When I try it I get an error, I think it's because the return statement is within the if and else statements.
The code is perfectly fine .. Error must be Somewhere else
public class Test1 {
public static void main(String[] args) {
System.out.println(multiple(3, 9));
}
public static boolean multiple(int m, int n){
int i = 0;
int j = 0;
boolean check = true;
if(n%m == 0){
i++;
return check;
}
else{
j++;
return false;
}
}
}
Output
true
here is output see IDEONE
The easiest way is to return the result of your if statement.
return n % m == 0;
I'm not sure what i/j are doing. You don't use them except to increment, but they are local to the function and get GC'd after the return. What you have now is basically this:
boolean bool = some_calculation();
if (bool == true)
{
return true;
}
else
{
return false;
}

How to speed up my prime calculations?

I'm trying to answer the following Euler Problem (#10):
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
My program is working correctly, however I found out that it took 100 seconds to compute this, using the following code, take new Problem10().run() as starting point:
public class Problem10 extends Problem<Long> {
#Override
public void run() {
result = Iterators.finiteLongStream(new PrimeGenerator(), i -> i <= 2_000_000)
.sum();
}
#Override
public String getName() {
return "Problem 10";
}
}
public abstract class Iterators {
///
public static PrimitiveIterator.OfLong finiteLongIterator(final PrimitiveIterator.OfLong iterator, final LongPredicate predicate) {
return new PrimitiveIterator.OfLong() {
private long next;
#Override
public boolean hasNext() {
if (!iterator.hasNext()) {
return false;
}
next = iterator.nextLong();
return predicate.test(next);
}
#Override
public long nextLong() {
return next;
}
};
}
public static LongStream finiteLongStream(final PrimitiveIterator.OfLong iterator, final LongPredicate predicate) {
return Iterators.longStream(Iterators.finiteLongIterator(iterator, predicate));
}
public static LongStream longStream(final PrimitiveIterator.OfLong iterator) {
return StreamSupport.longStream(
Spliterators.spliteratorUnknownSize(iterator, 0), false
);
}
///
}
public class PrimeGenerator implements PrimitiveIterator.OfLong {
private final static LongNode HEAD_NODE = new LongNode(2);
private LongNode lastNode = HEAD_NODE;
private long current = 2;
#Override
public boolean hasNext() {
return true;
}
#Override
public long nextLong() {
if (lastNode.value == current) {
if (lastNode.next != null) {
long old = lastNode.value;
lastNode = lastNode.next;
current = lastNode.value;
return old;
}
return current++;
}
while (true) {
if (isPrime(current)) {
appendNode(current);
return current++;
}
current++;
}
}
private boolean isPrime(final long number) {
LongNode prime = HEAD_NODE;
while (prime != null && prime.value <= number) {
if (number % prime.value == 0) {
return false;
}
prime = prime.next;
}
return true;
}
private void appendNode(final long value) {
LongNode newNode = new LongNode(value);
couple(lastNode, newNode);
lastNode = newNode;
}
private void couple(final LongNode first, final LongNode second) {
first.next = second;
second.previous = first;
}
private static class LongNode {
public final long value;
public LongNode previous;
public LongNode next;
public LongNode(final long value) {
this.value = value;
}
}
}
How could I optimise this? If possible, first suggestions along the lines of my current code, then suggesting a totally different algorithm.
Edit, also I'd like to refrain from a finite Sieve of Eratosthenes, as the whole point of such an iterator resp. stream is to be able to do it for an infinite amount of prices, I am unsure myself whether the Sieve of Eratosthenes method works for infinite numbers, I think not trivially.
The number of iterations in the method isPrime() can be reduced if you observe the fact that only the prime factors less than square root of a number need to be considerd.
So the current condition is :
while (prime != null && prime.value <= number)
It can be changed to :
while (prime != null && prime.value <= square_root(number) )
There might be other possibilities to optimize your code but that would need detailed review of your code.
Here are some thoughts (not code since this appears to be a homework / project problem):
Compute with ints not longs (int is good enough to hold 2 000 000) Though your sum of primes may need to be a long
Only check odd numbers starting with 3 in your loop (why check an even number that you know is not prime>!
Ensure you use minimum code possible .. there are lots of structures in your code. Wouldn't a simple loop over int values (and checking primes you have found only up to the sqrt of your value?)
And don't use square root function. Instead calculate the index of the largest prime you have to check as prime[p]*prime[p] so long as that is greater than your trial value. For example use something like this in your code (where ps is the index of the first prime you are checking, and iMax is primes[ps]*primes[ps] before you get into the loop. For efficiency of time, always use "strengh reductions" of calculations when you can.
while (i > iMax) {
ps++; iMax = primes[ps]*primes[ps];
};

While loop not working properly for even/idd numbers

My assignment is to create a method that returns true if my set of integers has an un-even number in it. My problem is that even if I have un-even numbers in my set, it will return false. Where am i making a mistake?
import java.util.*;
public class Chapter_11_E9
{
public static boolean odd;
public static boolean hasOdd(Set<Integer> tSet1)
{
Iterator<Integer> itr = tSet1.iterator();
while (itr.hasNext())
{
int current = itr.next();
if ((current / 2) == 1)
{
odd = true;
}
else
{
odd = false;
}
}
return odd;
}
public static void main(String[] args)
{
Set<Integer> tSet1 = new HashSet<Integer>();
tSet1.add(6);
tSet1.add(2);
tSet1.add(5);
tSet1.add(4);
tSet1.add(12);
tSet1.add(6);
tSet1.add(14);
System.out.println(tSet1);
System.out.println(hasOdd(tSet1));
}
}
This line:
if ((current / 2) == 1)
Should be:
if ((current % 2) == 1)
/ is for diving and % is for getting the remainder. Also, your method logic is off. Say you have multiple odds and evens in the set, you could get wrong results. I'd recommend doing this:
public static boolean hasOdd(Set<Integer> tSet1)
{
Iterator<Integer> itr = tSet1.iterator();
while (itr.hasNext())
{
int current = itr.next();
if ((current % 2) == 1)
{
//odd = true;
return true;//once you find the odd, just return
}
//else
//{
// odd = false;
//}
}
//return odd;
//if you're done iterating, that means it never found an odd so return false
return false;
}
Once you've found one odd in the set, then your case is true. Once you've looped through the entire set, then you know there could haven't been any odds, so just return false.
Note: As user ZouZou mentioned, if you want to handle negatives, then use:
current%2 != 0
You need to return the first time you get an odd value (as is you'll only return true if the last item is odd).
public static boolean hasOdd(Set<Integer> tSet1)
{
Iterator<Integer> itr = tSet1.iterator();
while (itr.hasNext())
{
int current = itr.next();
if ((current % 2) != 0) // Check for odd, by computing the modulo 2 of the #.
{
return true; // stop, there is an odd value.
}
}
return false; // checked all the values... none are odd.
}
I would use for-each loop here
public static boolean hasOdd(Set<Integer> set) {
for (Integer current : set) {
// Check for odd, by computing the modulo 2 of the #.
if ((current % 2) != 0) {
// stop, there is an odd value.
return true;
}
}
// checked all the values... none are odd.
return false;
}

Categories

Resources