Hello! can anybody please tell me the formula through which i can make the prime number program. I couldn't found the logic of it.

jwenting commented: lazy homework kiddo -3

Recommended Answers

All 4 Replies

import java.io.*;

/*Prime number is that kind of number
which divisible by only 1 and itself*/

public class PrimeNumber 
{
    public static void main(String args[])throws IOException
    {
        double num;
        int flag=0;
        System.out.println("Enter the number to check whether it is prime or not:");
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
        num=Double.parseDouble(bufferedReader.readLine());
                                                                              /*so we have to check starting from 2 upto square root of the number
 you can check manually,if a number is not going to be divisible upto 
the square root of the same number starting from 2,then it will not
 going to be divided by any other number above than the square root and lesser that the input*/
        for(int i=2;i<=Math.sqrt(num);i++)
        {
            if(num%i==0)
            {
                flag=1;
            }
        }
        if(flag==0)
            System.out.println(num +" is a prime number");
        else
            System.out.println(num +"is not a prime number");

    }
}
commented: don't help homework kiddos -3

If OP really doesn't have sufficient ability or initiative to find information on prime number programs on the web then simply giving them something to copy & paste into their homework is helping nobody. Not their teacher, not a potential employer, not their hard working colleagues, and least of all not the OP.

ps: Anyone thinking of using subhraakasuny's code should also be aware that it's a poor example of Java code. An int called "flag" that just has values 0 and 1 clearly identifies someone who (a) doesn't care about variable naming and (b) hasn't heard of booleans. It's also inefficient (tries modulo by every number when it only needs primes or at the very least just odd numbers after two; keeps going even after proving num is not prime).

commented: Being a beginner,It is really helpful to me to understand the fault. +0

well, it may help him get a job for a few weeks until he gets fired for incompetence. Which might yield him a paycheck of unearned wages for that period, at the expense of qualified people who now end up not only unemployed and poorer but suspect of being unqualified as well.

Prime no is a no which is divide by 1 and its own.

E.G. 1,2,3,5,7,11.....

commented: 1 is not a prime number +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.