71.9k views
4 votes
Write a program that prompts the user for an integer and then prints all prime numbers up to that integer.

User Rosejn
by
5.4k points

2 Answers

2 votes

Final answer:

To write a program that prints all prime numbers up to a given integer, use a loop to iterate through each number and check if it is prime by dividing it by all numbers from 2 up to its square root.

Step-by-step explanation:

To write a program that prints all prime numbers up to a given integer, you can use a loop to iterate through each number from 2 up to the given integer. For each number, you can check if it is prime by dividing it by all numbers from 2 up to its square root. If the number is divisible by any of these numbers, it is not prime and you can move on to the next. Otherwise, it is prime and you can print it.

Here's an example implementation in Python:

def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

n = int(input('Enter an integer: '))
for i in range(2, n + 1):
if is_prime(i):
print(i)

In this example, the is_prime() function checks if a number is prime, and the main program prompts the user for an integer and prints all prime numbers up to that integer.

User Hexist
by
5.2k points
0 votes

Answer:

import java.util.Scanner;

public class New

{

public static void main(String[] args)

{

int num;

int prime;

Scanner var=new Scanner(System.in);

System.out.println("Enter a number: ");

num=var.nextInt();

for(int i=2;i<num;i++)

{

prime=0;

for(int j=2;j<i;j++)

{

if(i%j==0)

prime=1;

}

if(prime==0)

System.out.println(i);

}

}

}

Step-by-step explanation:

Using Java Programming Language the program as implemented above will prompt a user to enter a number, for example the user enters 5,

It will print

2

3

which are the prime numbers up to the integer 5

User Marcantonio
by
4.8k points