Need Simple, Basic, Fundamental introductory beggining skills used. [Book:starti
ID: 3565982 • Letter: N
Question
Need Simple, Basic, Fundamental introductory beggining skills used.
[Book:starting out with java from control struct through objects]
Programming Challenge - Ch. 5: isPrime Method and Prime Number List
See pages 293 & 294: isPrime Method and Prime Number List
A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it can only be evenly divided by 1 and 5 The number 6, however, is not prime because it can be divided evenly by 1, 2, 3, and 6.
Write a method named isPrime, which takes an integer as an argument and returns true if the argument is a prime number, or false otherwise. Use the isPrime method in a program that prints a list of all the prime numbers from 1 through 100.
Explanation / Answer
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Prime
{
boolean isPrime(int n)
{
int i =0;
for(i=2;i<n;i++)
{
if(n%i==0)
return false;
}
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Prime o = new Prime();
System.out.println(o.isPrime(7));
int j;
for(j=1;j<101;j++)
{
if(o.isPrime(j))
{
System.out.println(j);
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.