Tuesday, July 28, 2009

How do you write a java program that asks you for a integer and prints out all the prime numbers below it?

can someone help me out please? I've been working on this assignment for days...i know what prime number is but i just do not know how to program that...All i know is it is related to that loop structure in java.

How do you write a java program that asks you for a integer and prints out all the prime numbers below it?
What do you need help with? Getting a number from the user, or looping?





1. Get an int from the user


2. use a for-loop and decrement down to zero


3. check if current number is prime and print it if it is.


4. end loop





5. Have a function that takes an int and returns a boolean that says whether the int is prime or not.





If you need more help, you can send an email to me.
Reply:// This function returns whether the number n is prime or not.





public static boolean isPrime(final int n) {


int limit = (int) ((Math.sqrt(n))+1);


for (int i = 2; i %26lt;= limit; i++) {


if ((n % i) == 0) {


return false;


}


}


return true;


} Report It

Reply:The key part of this program is the following loop (assume that x is your input)





for(int i = 1; i %26lt; x; i++)


{


boolean prime = true;


for(int j = 2; ((j %26lt; i) %26amp;%26amp; (prime == true)); j++)


{


if( int(i/j) * j == i)


{


prime = false;


}


}


if( prime == true)


{


System.out.print(Integer.toString(i) + " is prime");


}


}
Reply:import java.io.*;


class prime


{


public static void main(String arr[])throws Exception


{


DataInputStream dis=new DataInputStream(System.in);


System.out.print("Enter the range::");


int n=Integer.parseInt(dis.readLine()),count...


for(int i=2;i%26lt;=n;i++)


{


count=0;


for(int j=2;j%26lt;i;j++)


if(i%j==0)


count++;


if(count==0)


System.out.println(i);


}


}


}
Reply:import java.io.*;


class Prime


{


public static void main(String args[])throws IOException


{


DataInputStream d=new DataInputStream(System.in);


int num,count=0;


System.out.println("enter the value upto which to find prime numbers");


num=Integer.parseInt(d.readLine( ) );


System.out.println("prime numbers till "+num+" are");


for(int i=2;i%26lt;=num;i++)


{


count=0;


for(int j=2;j%26lt;=i;j++)


{


if(i%j==0)


count++;


}


if(count==1)


System.out.println(i);


}


}


}


No comments:

Post a Comment