자바 언어 프로그래밍 기초 제6장 연습문제

2994 단어
6.26 패키지 방법2;
public class 메시지 수
public static void main(String[] args) {

//TODO Auto-generated method stub
	for (int i = 2; i <= 1000; i++) {

		if (isprime(i) == 1 && getprime(i) == 1)

			System.out.println(i);

	}

}

public static int isprime(int n)

{

	int flag = 1;

	for (int i = 2; i < n; i++)

	{

		if (n % i == 0) {
			flag = 0;
			break;
		}

		else
			flag = 1;

	}

	return flag;

}

public static int getprime(int n)

{

	if (n < 0)
		return 0;

	int div = 1;

	while (n / div >= 10) {

		div *= 10;

	}

	while (n != 0) {

		int l = n / div;

		int r = n % 10;

		if (l != r)
			return 0;

		n = (n % div) / 10;

		div /= 100;

	}

	return 1;

}

}6.28 메슨소수 패키지 방법2;
public class 메센셜 수 {
public static void main(String[] args) {
	// TODO Auto-generated method stub
	System.out.println("P            2^P-1");
	int number = 2;
	for (int p = 0; p <= 31; number++) {
		if (isSuShu(number)) {
			if (isMeiSenSuShu(number)) {
				p = getP(number);
				System.out.printf("%8d", p);
				long sum = (long) (Math.pow(2, p) - 1);
				System.out.printf("%8d
", sum); } } } } public static boolean isSuShu(int n) { boolean flag = true; for (int i = 2; i < n; i++) { if (n % i == 0) flag = false; break; } return true; } public static boolean isMeiSenSuShu(int number) { // true for (int p = 0; p < 1000; p++) { if (Math.pow(2, p) == number + 1) return true; } return false; } public static int getP(int number) { // P for (int p = 0; p < 1000; p++) { if (Math.pow(2, p) == number + 1) return p; } return -1; }

} 6.31 import java.util.Scanner;
public class kahao { public static void main(String[] args) {//TODO Auto-generated method stub Scanner input = new Scanner(System.in); System.out.println(“Enter your card number”); String s = input.nextLine(); int a; if (isValid(s) && prefixMatched(s)) { a = sumOfDoubleEvenPlace(s) + SumOfOddPlace(s); if (a % 10 == 0) { System.out.println(s + "is valid"); } else System.out.println(s + "is invalid"); } else System.out.println(s + "is invalid"); }
public static boolean isValid(String s) {
	if (s.length() >= 13 && s.length() <= 16)
		return true;
	else
		return false;
}

public static int sumOfDoubleEvenPlace(String s) {
	int m = 0;
	for (int i = s.length() - 2; i >= 0; i -= 2) {
		int k = (s.charAt(i) - 48) * 2;
		if (k >= 10) {
			k = k % 10 + k / 10;
		}
		m += k;
	}
	return m;
}

public static int SumOfOddPlace(String s) {
	int n = 0;
	for (int i = s.length() - 1; i >= 0; i = i - 2) {
		n += (s.charAt(i) - 48);
	}
	return n;
}

public static boolean prefixMatched(String s) {
	if (s.charAt(0) == 52 || s.charAt(0) == 53 || s.charAt(0) == 54 || (s.charAt(0) == 51 && s.charAt(1) == 49)) {
		return true;
	} else
		return false;
}

}

좋은 웹페이지 즐겨찾기