This site requires JavaScript, please enable it in your browser!
Greenfoot back
MRCampbell
MRCampbell wrote ...

2021/9/19

Greenfoot.stop() not stoping the execution

MRCampbell MRCampbell

2021/9/19

#
This code finds the largest prime factor of a given long called "dividend". It starts by dividing "dividend" by dividen/2. If the number is a factor, then it checks if it is prime. Once it finds a prime number it should stop the execution, but the code continues. Please advise, thanks.
MRCampbell MRCampbell

2021/9/19

#
As I wrote the description up above, I came up with a much simpler solution. I also included the isItPrime() method.
public class Euler3a extends Actor
{
    /**
     * Act - do whatever the Euler3a wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        System.out.println("Starting Program");
        //long dividend = 600851475143L;
        long dividend = 100L;
        for(long i = 2; i < dividend/2; i++)
        {
            if(dividend % i == 0)
            {
                if(isItPrime(dividend / i))
                {
                    System.out.println("Found It! " + dividend / i);
                    Greenfoot.stop();
                }
            }
        }
        
        System.out.println("Program End");
    }
    public boolean isItPrime(long num)
    {
        System.out.print(" Is " + num + " prime: ");
        long start = num / 2;
        for(long i = start; i>1; i--)
        {
            //System.out.println("  Checking " + num + " / " + i);
            if(num % i == 0)
            {
                System.out.println("False");
                return false;
            }
        }
        System.out.println("True");
        return true;
    }
}
You need to login to post a reply.