Welcome to Dream.In.Code
Become a Java Expert!

Join 150,429 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,079 people online right now. Registration is fast and FREE... Join Now!




Logic error with prime numbers?

 
Reply to this topicStart new topic

Logic error with prime numbers?

myra
5 Apr, 2008 - 01:30 AM
Post #1

New D.I.C Head
*

Joined: 4 Apr, 2008
Posts: 25


My Contributions
Hi,

I am required to do a program to determine prime numbers. These are the formulas I'm using:

i) if number % factor = 0 || number = 1 || number = 0,
then the number is not a prime
ii) int highestPossibleFactor = (int)(Math.sqrt(Number)) to determine the square root of a number.

The following segment is what I've written in my code so far:

CODE
{  
            System.out.printf("\nEnter an integer value: ");
            int number = keyboard.nextInt();
            double highestPossibleFactor = (int) (Math.sqrt(number));
            {if (number % highestPossibleFactor == 0 || number == 0 ||
                    number == 1)
                System.out.printf(number+ " is not a prime!\n\n ");
            else
                if (number % highestPossibleFactor !=0 || number !=1 ||
                        number != 0)
                System.out.printf(number+ " is a prime!\n\n ");
            }


I am able to execute the program but every number I placed for the input(even numbers like 2) gets the output of "not a prime number." Is there something wrong with the way I placed the formula? How do I place a loop in this code? Thank you for your time.
User is offlineProfile CardPM
+Quote Post

KYA
RE: Logic Error With Prime Numbers?
5 Apr, 2008 - 01:55 AM
Post #2

#include <nerd.h>
Group Icon

Joined: 14 Sep, 2007
Posts: 5,955



Thanked: 160 times
Dream Kudos: 1375
My Contributions
Need to have () around each portion between the ORS and I would change it to a cascaded if else statement since you used if originally

CODE

if (number % factor == 0)
// code
else if (number % factor == 1)
//code
else if (number % factor == 2)


You could also use a switch statement

edit: changed to assignment operators--stupid me

This post has been edited by KYA: 5 Apr, 2008 - 02:16 AM
User is online!Profile CardPM
+Quote Post

pbl
RE: Logic Error With Prime Numbers?
5 Apr, 2008 - 06:44 AM
Post #3

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,594



Thanked: 233 times
Dream Kudos: 75
My Contributions
May be I am not really awake but...

you have to test from 2 to the highestPossibleFactor

there is a loop missing here


User is online!Profile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/9/09 08:53PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month