420-D01-SU Practical Project 2: Prime Number Algorithm in Java

Verified

Added on  2022/08/15

|3
|331
|17
Practical Assignment
AI Summary
This document presents a Java program designed to identify and display all prime numbers within a specified range (1 to 50,000). The program includes comprehensive components, beginning with the Java code itself, which takes an integer input 'n' from the user and then iterates from 1 to 'n', checking each number for primality. The core logic involves counting the number of divisors for each number and determining if the count is exactly two (1 and the number itself), which indicates a prime number. The program constructs a string 'primeNumbers' to store and output the identified prime numbers. Accompanying the code is an analysis section that explains the program's functionality and design decisions. Further, a pseudocode representation provides a high-level, language-agnostic description of the algorithm. Finally, a detailed trace table is included to demonstrate the program's execution flow, showing the values of key variables at each step of the process for a sample input value (n=20), facilitating understanding and debugging. This assignment is from a practical project in the course 420-D01-SU Algorithms and infrastructure.
Document Page
Question 46: Program for displaying all prime numbers from 1 to 50,000
import java.util.Scanner;
public class Prime {
public static void main (String args[])
{
Scanner sc = new Scanner(System.in);
int i =0;
int num =0;
String primeNumbers = "";
System.out.println("Enter the value of n:");
int n = sc.nextInt();
sc.close();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
counter = counter + 1;
}
}
if (counter ==2)
{
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to n are :");
System.out.println (primeNumbers);
}
}
Trace table
Step Statement Notes n num primeNumbers coun
ter
1 num=0; Initialise the
value of
num=0.
? 0 ? ?
2 n=20 Put the value
of n=20.
20 0 ? ?
3 for (i = 1; i <= n; i++) Start the for 20 0 ? ?
Document Page
loop until
i<=n.
4 counter=0; Initialise the
value of
counter=0.
20 0 ? 0
5 for(num=i;num>=1;nu
m--)
Start the for
loop until
num>=1.
20 0 ? 0
6 if(i%num==0)
{counter=counter + 1;}
if (i%num==0)
the calculate
the value of
counter=count
er+1.
20 0 ? 0
7 if(counter==2)
{primeNumbers=prime
Numbers + i + " ";}
if(counter==2)
then calculate
the value of
primeNumbers
=primeNumber
s+i..
20 0 {2,3,5,7,11,13,17,1
9}
2
8 System.out.println(prim
eNumbers)
Print the value
of
primeNumbers
.
chevron_up_icon
1 out of 3
circle_padding
hide_on_mobile
zoom_out_icon
[object Object]