MATHEMATICAL COMPUTING Use the program Spyder: (1) The goal is to find all the p
ID: 3788469 • Letter: M
Question
MATHEMATICAL COMPUTING
Use the program Spyder:
(1) The goal is to find all the prime numbers less than or equal to some natural number maxn.
We have a list that tells us if any of the numbers 0..maxn are "marked". It can be an array of booleans. The zero and one slots are not used.
Start with 2 and mark all the multiples of 2.
Find the next unmarked number d, mark all of its multiples, and so on.
You can stop when 2d>maxn, or there are no more unmarked numbers.
To print out the primes, print out all unmarked numbers.
Explanation / Answer
1) The goal is to find all the prime numbers less than or equal to some natural number maxn.
To print out the primes, print out all unmarked numbers.
package com.list;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
//The goal is to find all the prime numbers less than or equal to some natural number maxn.
//To print out the primes, print out all unmarked numbers
class PrimeNumber{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("find all the prime numbers less than or equal to some natural Enter the range : ");
int range=Integer.parseInt(br.readLine());
System.out.println();
ArrayList<Integer>prime=new ArrayList<Integer>();
Set<Integer>nonprime=new HashSet<Integer>();
for(int i=2;i<=range;i++)
{
int flag=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
{
nonprime.add(i);
flag=1;
}
}
if(flag==0){
prime.add(i);
//System.out.println("prime numbers");
// System.out.print(i+" ");
}
}
System.out.println("prime==="+prime);
System.out.println("nonprime===="+nonprime);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.