`
Brucegaochina
  • 浏览: 39691 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

1-1000内质数

阅读更多
定义:质数又称素数。指在一个大于1的自然数中,除了1和此整数自身外,没法被其他自然数整除的数。换句话说,只有两个正因数(1和自己)的自然数即为素数。比1大但不是素数的数称为合数。1和0既非素数也非合数。合数是由若干个质数相乘而得到的。所以,质数是合数的基础,没有质数就没有合数。

分析:所以在求素数的时候,在2-1000之间出了1和自身之外不能被其他数整除,当我们循环到i(2<=i<1000)时,只要i不能被[2-(i-1)]之间任何一个整数我们就可以判定这个数是素数,我们将其打印出来;同时我们还要统计除两个特殊的素数(2,5)以外的分别一1,3,7,9结尾的素数的个数个其占此间所有素数的比例。

代码如下:

import java.text.NumberFormat;

public class PrimitiveNumber {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int count = 0;
		int intOne = 0;
		int intThree = 0;
		int intSeven = 0;
		int intNine = 0;

		NumberFormat number = NumberFormat.getInstance();
		number.setMaximumFractionDigits(2);
		for (int i = 2; i < 1000; i++) {
			boolean flag = true;
			for (int j = 2; j < i; j++) {
				if (i % j == 0)
					flag = false;

			}
			if (flag) {
				count++;
				if (i % 10 == 1)
					intOne++;
				if (i % 10 == 3)
					intThree++;

				if (i % 10 == 7)
					intSeven++;
				if (i % 10 == 9)
					intNine++;

				System.out.print(i + " ");
			}

		}
		System.out.println();
		System.out.println("The total prime number among 1-1000 is: " + count);
		// except 2 and 5
		count = count - 2;
		System.out.println("The percent of end with 1 is: " + intOne + ", "
				+ number.format((float) intOne / (float) count * 100) + "%");
		System.out.println("The percent of end with 3 is: " + intThree + ", "
				+ number.format((float) intThree / (float) count * 100) + "%");
		System.out.println("The percent of end with 7 is: " + intSeven + ", "
				+ number.format((float) intSeven / (float) count * 100) + "%");
		System.out.println("The percent of end with is 9: " + intNine + ", "
				+ number.format((float) intNine / (float) count * 100) + "%");

	}

}



结果:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 
The total prime number among 1-1000 is: 168
The percent of end with 1 is: 40, 24.1%
The percent of end with 3 is: 42, 25.3%
The percent of end with 7 is: 46, 27.71%
The percent of end with is 9: 38, 22.89%


问题:想想如果想打印出的结果是合数;又该怎么做呢?
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics