Professional Documents
Culture Documents
Enter a number
465
465 = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 + 21 +
22 + 23 + 24 + 25 + 26 + 27 + 28 + 29 + 30
Enter a number
8
-1
IV. Create a program to check whether a number is circular prime.
Code :
import java.util.*;
class circular
{
static boolean Prime(int n)
{
int flag=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
flag++;
}
if(flag==2)
return true;
else
return false;
}
static boolean circprime(int N)
{
int count = 0, temp = N, num = N;
for(;temp>0; temp /= 10)
count++;
while (Prime(num)==true)
{
int rem = num % 10;
int div = num / 10;
num = (int)((Math.pow(10, count-1))*rem)+div;
if (num == N)
return true;
}
return false;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number.");
int N = sc.nextInt();
if (circprime(N))
System.out.println("Entered number is a circular prime");
else
System.out.println("Entered number is NOT a circular prime");
}}
Sample Output :
Enter a number.
1193
Entered number is a circular prime
Enter a number.
113
Entered number is a circular prime
Enter a number.
23
Entered number is NOT a circular prime
V. Create a program to shift rows of a matrix (upwards).
Code :
import java.util.*;
class shift
{
int r,c,s;
int ar[][];
Scanner sc=new Scanner(System.in);
shift(int rr, int cc, int ss)
{
s=ss; r=rr; c=cc;
ar=new int[r+1][c];
}
void input()
{
System.out.println("Enter elements of matrix.");
for(int i=1; i<r+1; i++)
{
for(int j=0; j<c; j++)
ar[i][j]=sc.nextInt();
}
}
void process()
{
for(int sh=1; sh<=s; sh++)
{
for(int i=1; i<r+1; i++)
{
for(int j=0; j<c; j++)
ar[i-1][j]=ar[i][j];
}
for(int i=0; i<c; i++)
ar[r][i]=ar[0][i];
}
}
void display()
{
for(int i=1; i<r+1; i++)
{
for(int j=0; j<c; j++)
System.out.print(ar[i][j]+" ");
System.out.println();
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter dimensions of matrix.");
int rr=sc.nextInt();
int cc=sc.nextInt();
System.out.println("Enter no. of rows to be shifted.");
int ss=sc.nextInt();
shift ob=new shift(rr,cc,ss);
ob.input();
System.out.println("Before shifting :");
ob.display();
ob.process();
System.out.println("After shifting :");
ob.display();
}
}
Samole Output :
Enter dimensions of matrix.
3
3
Enter no. of rows to be shifted.
2
Enter elements of matrix.
1
2
3
4
5
6
7
8
9
Before shifting :
1 2 3
4 5 6
7 8 9
After shifting :
7 8 9
1 2 3
4 5 6