Write a program to find the prime numbers
- Ask user to input the integer number
- test the number whether it is a prime number or not
- Then, print “true” or “false” depending on whether the number is prime or isn’t.
- Hint: number is prime when is has exactly 2 factors: one and itself. By this definition, number 1 is a special case and is NOT a prime.
- Use idea of user input, cumulative sum, and loop to solve this problem. You can assume user inputs positive number.
• Ask user to input two integer parameters a, and b.
– Assume that a is a positive integer (>0) and b is single-digit numbers from 0-9 inclusive.
– Your program should print:
• true if a contains b at among its digits, and
• false otherwise.
– For example when a is 3415, b is 1, should print true.
– (Note: You can not use a String to solve this problem. )
PROGRAMMING LANGUAGE - JAVA
PART 1
CODE -
import java.util.Scanner;
public class prime {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Initialize count of factors to 0
int countFactors = 0;
int num;
// Take a number as input from user
System.out.print("Enter a number: ");
num = keyboard.nextInt();
// Loop to count number of factors
for(int i=1; i<=num; i++)
// If the number is divisible by a number increase the count of factors
if(num%i == 0)
countFactors += 1;
// Number is prime if number of factors is equal to 2
if(countFactors == 2)
System.out.println("True");
else
System.out.println("False");
keyboard.close();
}
}
SCREENSHOT -
PART 2
CODE -
import java.util.Scanner;
public class containDigit {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int num, digit;
// Take a positive number as input from the user
System.out.print("Enter a positive integer: ");
num = keyboard.nextInt();
// Take a single-digit positive integer as input from user
System.out.print("Enter a single-digit integer(0-9): ");
digit = keyboard.nextInt();
// Initialize contain variable to false
boolean contain = false;
// Loop to check if the number contain the entered number among its digit
while(num>0)
{
int d = num%10;
// Set the variable contain to true if the current digit of the number is equal to the second number(entered by user)
if (digit == d)
{
contain = true;
break;
}
num = num/10;
}
System.out.println(contain);
keyboard.close();
}
}
SCREENSHOT -
If you have any doubt regarding the solution or if you
want the solution to be in a different programming language, then
do comment.
Do upvote.
Get Answers For Free
Most questions answered within 1 hours.