Nearest Smallest Prime
- Program to find the nearest smaller prime number for a given integer; use a function to decide whether a number is prime or not.
Program
import
java.util.Scanner;
public class
NearPrime {
private static
Scanner sc;
static int num;
public int
prime(int j) {
int
flag=0;
for(int
i=1;i<=j;i++) {
if(j%i==0)
{
flag++;
}
}
if(flag==2)
{
System.out.println("The
nearest smaller prime number for "+num+"
is "+j);
return 1;
}
else {
return 0;
}
}
public static void main(String[] args)
{
int
i,check=0;
sc=new
Scanner(System.in);
System.out.print("Enter
a number:");
num=sc.nextInt();
NearPrime ob = new
NearPrime();
for(i=num-1;i>=0;i--)
{
check=ob.prime(i);
if(check==1)
{
return;
}
}
if(check==0)
{
System.out.println("There
is no nearest smaller prime number for "+num+".");
}
}
}
Output
Enter
a number:89
The
nearest smaller prime number for 89 is 83
Program
to convert a number in decimal system to binary system. Hint: use recursion.
Program
import
java.util.Scanner;
public class
DecimalToBinary {
private static
Scanner assign;
public static void
main(String[] args) {
int
dec;
assign=new
Scanner(System.in);
System.out.println("Enter
a decimal value:");
dec=assign.nextInt();
System.out.println("The
binary value of "+dec+" is:");
DecimalToBinary ob=new
DecimalToBinary();
ob.compute(dec);
}
public void
compute(int dec) {
if(dec>0)
{
compute(dec/2);
System.out.print(dec%2+"
");
}
}
}
Output
Enter
a decimal value:
98
The
binary value of 98 is:
1 1 0 0 0 1
0
No comments:
Post a Comment