This is the program that he gave us. // find all primes < 1M using BRUTE FORCE,
ID: 3742900 • Letter: T
Question
This is the program that he gave us.
// find all primes < 1M using BRUTE FORCE, checking
// ALL whole numbers less than square root as possible
// factors of 'n'
public class Lab2
{
public static boolean isPrime(int n)
{
int root = (int) Math.sqrt(n);
for (int i=2; i<=root; i++) {
if ((n%i) == 0)
{
return false;
}
}
return true;
}
public static void main(String args[])
{
int c=0;
long start, end, mstime;
final int LIMIT=1000000; // 1M took ~800 secs.
start = System.currentTimeMillis();
for (int i=2; i<LIMIT; i++) {
if (isPrime(i)) {
System.out.println(i);
c++;
}
}
end = System.currentTimeMillis();
mstime = end - start;
System.out.println("#primes = " + c + ", mstime = " + mstime);
}
}
Explanation / Answer
This is almost solved. please let me know if any further modificatins are needed.
Code:
// find all primes < 1M using BRUTE FORCE, checking
// ALL whole numbers less than square root as possible
// factors of 'n'
public class Main{
// function to check a number is prime or not
public static boolean isPrime(int n){
// finding the square root of the number
int root = (int) Math.sqrt(n);
// checking for factors between 2 and root of
// that number
for (int i=2; i<=root; i++) {
if ((n%i) == 0){
return false;
}
}
return true;
}
// writing main function to check the primes
public static void main(String args[]){
int c=0;
long start, end, mstime;
// taking thee limit as 1M
final int LIMIT=1000000; // 1M took ~800 secs.
// noting down starting time
start = System.currentTimeMillis();
for (int i=2; i<LIMIT; i++) {
// checking the number and printing it i it is prime
if (isPrime(i)) {
System.out.println(i);
c++;
}
}
// endi time
end = System.currentTimeMillis();
// total time took to calculate the primes
mstime = end - start;
// final output of the programm
System.out.println("#primes = " + c + ", mstime = " + mstime);
}
}
Output:
output is too large to be posted. try to execute it once and u will get the results. if any doubts are there please comment and let me know.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.