求最大质因数
package day1;
public class maxPrime {
public static void main(String[] args) {
System.out.println(maxprimeFactor(600851475143L));
}
public static long maxprimeFactor(long number){
if(number==1)
return 1;
for(int i=2;i<number;i++){
if(number % i==0)
return maxprimeFactor(number/i);
}
return number;
}
}
直接输出600851475143会出现整数过大的错误,默认情况下,java将所有数字文字解释为32位整数值。如果想明确地指定这是更大的那么32位整数应该使用后缀L的长值。
求三位数的最大回文数
package day1;
public class maxHuiWen {
public static void main(String[] args) {
System.out.println(cal());
}
public static int cal() {
int result = 0;
for (int i = 999; i >= 100; i--)
for (int j = 999; j >= i; j--) { //j>=i避免重复计算
int s = i * j;
if (s > result && p(s))
result = s;
}
return result;
}
private static boolean p(int result){
int maxnum = 0;
int a[] = new int[10];
while (result != 0){
a[maxnum++] = result%10;
result /= 10;
}
for (int i=0;i<maxnum>>1;i++){
if(a[i] != a[maxnum -i -1])
return false;
}
return true;
}
}
package day1;
public class maxHuiWen {
public static void main(String[] args) {
System.out.println(getPalindromicNumber());
}
private static Long getPalindromicNumber() {
Long max = 0L;
for (Long i = 100L; i <= 999; i++) {
for (Long j = 100L; j <= 999; j++) {
if (isPalindromicNumber(i * j)) {
if (i * j > max) {
max = i * j;
}
}
}
}
return max;
}
private static boolean isPalindromicNumber(Long n) {
StringBuffer s = new StringBuffer(n + "");
s.reverse();
return Long.parseLong(s.toString()) == n;
}
}