Repository navigation
Expand file tree
/
Copy pathBai4.java
More file actions
105 lines (75 loc) · 2.33 KB
/
Copy pathBai4.java
File metadata and controls
105 lines (75 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package Chuong1b;
import java.util.Scanner;
public class Bai4 {
public static boolean prime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i <= n / i; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Nhap so tu nhien N: ");
int n = sc.nextInt();
if (n < 0) {
System.out.println("N phai la so tu nhien.");
sc.close();
return;
}
// Cau a: Cac so tu nhien <= N va tong
long sumA = 0;
System.out.print("a. Cac so tu nhien <= N: ");
for (long i = 0; i <= n; i++) {
System.out.print(i + " ");
sumA += i;
}
System.out.println("\nTong: " + sumA);
// Cau b: Cac so tu nhien chan <= N va tong
long sumB = 0;
System.out.print("\nb. Cac so tu nhien chan <= N: ");
for (long i = 0; i <= n; i += 2) {
System.out.print(i + " ");
sumB += i;
}
System.out.println("\nTong: " + sumB);
// Cau c: Cac so tu nhien le <= N va tong
long sumC = 0;
System.out.print("\nc. Cac so tu nhien le <= N: ");
for (long i = 1; i <= n; i += 2) {
System.out.print(i + " ");
sumC += i;
}
System.out.println("\nTong: " + sumC);
// Cau d: Cac so nguyen to <= N va tong
long sumD = 0;
System.out.print("\nd. Cac so nguyen to <= N: ");
for (long i = 2; i <= n; i++) {
if (prime((int) i)) {
System.out.print(i + " ");
sumD += i;
}
}
System.out.println("\nTong: " + sumD);
// Cau e: N so nguyen to dau tien
int count = 0;
long num = 2;
System.out.print("\ne. " + n + " so nguyen to dau tien: ");
while (count < n && num <= Integer.MAX_VALUE) {
if (prime((int) num)) {
System.out.print(num + " ");
count++;
}
num++;
}
System.out.println();
if (count < n) {
System.out.println("Da vuot pham vi so nguyen int.");
}
sc.close();
}
}