0
public class Square
{
static void main()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int n = in.nextInt();
int sq = 0;
int rem, d;
for(int i = 2; i<=n; i++)
{
sq = i*i;
rem = 0;
d = 0;
while(rem<sq)
{
d = sq%10;
rem = (rem*10) + d;
sq = sq/10;
}
if(rem == i)
{
System.out.println(i);
}
}
}
}
5 answers
2
The numbers you are trying to get through this code are known as Automorphic numbers i.e. numbers which are contained in their square at the right side. Your solution was mostly correct except for a few places which I have commented and made some additions. Feel free to ask if you don't get any step.
import java.util.*;
public class Square
{
static void main()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int n = in.nextInt();
int sq = 0;
int rem, d,p;
for(int i = 2; i<=n; i++)
{
sq = i*i;
// rem = 0;
d = 0;
// while(rem<sq)
p=i;
while(p>0)
{
// d = sq%10;
// rem = (rem*10) + d;
d++; //Count the digits in the number
// sq = sq/10;
p = p /10;
}
//Now we need to take out 'd' digits from the square of the number
rem = sq % (int) Math.pow(10,d);
// if(rem == i)
if(rem == i)
{
System.out.println(i);
}
}
}
}
0
import java.util.*;
class number
{
public static void main(String args[])throws InputMismatchException
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the upper limit.");
int n=sc.nextInt();
int i,sq,a,b,p,c=0;
for(i=1;i<=n;i++)
{
sq=i*i;
p=sq;
while(p>0)
{
p/=10;
c++;
}
b=sq%(int)Math.pow(10,c-1);
if(b==i)
System.out.println(b);
}
}
}
0
0
Here is the corrected form of your program
import java.util.*;
class hjhj
{
public static void main(String args[])throws InputMismatchException
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the upper limit.");
int n=sc.nextInt();
int i,sq,b,p,c=0;
for(i=1;i<=n;i++)
{
c=0;
sq=i*i;
p=i;
while(p>0)
{
p=p/10;
c++;
}
b=sq%(int)(Math.pow(10,c));
if(b==i)
System.out.println(i);
}
}
}
0
Log in to your account to answer this questions.