Given an integer:
1,Divisibility: Is the number devisible by some other integer?
2, Length: How many digits are there in the number?
3, Reverse the integer: 123 --> 321
4,
Divisibility
If \(N\) is divisible by another integer \(k\), we can use following relational expression:
(N % k == 0)
If the remainder of \(N\) divided by \(k\) is \(r\), we can use following relational expression:
(N % k == r)
If \(p\) is a prime, then none of the integer between \(2\) and \(p-1\) can divide \(p\). Therefore, we can use a loop to test whether an integer \(p\) is a prime.
Length
Howo to count the number of digits in an integer?
An integer \(N\) divided by 10 will drop the last digit. This can be done by doing an integer division (N /10). This process can be repeatedly done when the result is still non zero.
#include<stdio.h>
int main()
{
int n,t;
int length;
n = 1024;
//scanf("%d",&n);
t = n / 10;
length = 1; //Any integer has at least one digit, even if it is zero.
while (t)
{
t = t /10;
length++;
}
printf("The integer %d has %d digits",n,length);
return 0;
}
stdout
The integer 1024 has 4 digits
Reverse order of an integer
There are two things to do. One is to get the last digit, the other is to cut the last digit off.
1, How to get the last digit? Uh...remember % operator? n % 10 is the last digit.
2, How to cut the last digit off? n / 10, this integer division will cut the last digit off.
And we can repeat this process until the first digit is cut off.
Now, we get all digits from right to left. Next task is to assemble these digits into an integer with reverse order.
Obviously, two digit number ab can be calculated by a * 10 + b.
/* Reverse an integer */
#include<stdio.h>
int main()
{
int n,t;
int m;
n = 12345;
//scanf("%d",&n);
t = n;
m = 0;
while (t)
{
m = m * 10 + t % 10;
t = t /10;
}
printf("The reverse of %d is %d.\n",n,m);
return 0;
}
stdout
The reverse of 12345 is 54321.