编程基础07

多层枚举嵌套

没什么思路先进行暴力搜索

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
#include<iostream>

using namespace std;
// 多层嵌套枚举

int main()
{
// 1.两个骰子,求所有排列方案

for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= 6; j++){
cout << "(" << i << "," << j << ")";
}
cout << endl;
}



// 2.枚举2024年的每一天

int months[13] = { 0, 31, 28, 31, 30, 31, 30 ,31, 31, 30, 31, 30, 31 };
for (int i = 1; i <= 12; i++){
for (int j = 1; j <= months[i]; j++){
cout << i << "月" << j << "号 ";
}
cout << endl;
}


// 3.三位数,数位每一位不超过n且不相等,而且该三位数是奇数

int n = 7;

for (int i = 100; i <= 999; i++){// 条件
// a b c
//枚举百位
for (int i = 1; i <= n; i++){
// 枚举十位
for (int j = 0; j <= n; j++){
// 枚举个位
if (i == j) continue; // 跳过当前循环,继续下一次循环
for (int k = 1; k <= n; k += 2)
{
if (i != k && j != k) cout << i * 100 + j * 10 + k << endl;
}
}
}
return 0;
}

作业

679 计算自己活了多少天

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
#include<iostream>
using namespace std;

int months[13] = { 0, 31, 28, 31, 30, 31, 30 ,31, 31, 30, 31, 30, 31 };

int addOne(int year)
{
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) return 1;
return 0;
}

int func(int year, int month, int day)
{
int days = 0;
for (int i = 1; i < month; i++)
{
days += months[i];
}
if (month > 2)
{
days += addOne(year);
}
days += day;
return days;
}

int main()
{
// 1.定义变量,输入
int birthyear, birthmonth, birthday;
int nowyear, nowmonth, nowday;
cin >> birthyear >> birthmonth >> birthday;
cin >> nowyear >> nowmonth >> nowday;

// 2.计算整年的天数
int days = 0;
for (int i = birthyear; i < nowyear; i++)
{
// 1. 365
// 2. 闰年+1
days += 365 + addOne(i);
}

// 3.减去出生那年的天数
days -= func(birthyear, birthmonth, birthday);

// 4.加上现在这年的天数
days += func(nowyear, nowmonth, nowday);
cout << days << endl;
return 0;
}

1601 求正整数2和n之间的完全数

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
#include<iostream>
using namespace std;

int check(int i)
{
// 判断是否是完全数
int sum = 0;
for (int j = 1; j < i; j++)
{
if (i % j == 0)
{
sum += j;
}
}
return sum == i;
}

int main()
{
int n;
cin >> n;
for (int i = 2; i <= n; i++)
{
if (check(i))
{
cout << i << endl;
}
}
return 0;
}

1604 亲和数

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
#include<iostream>
using namespace std;

int fac_sum(int x)
{
int sum = 0;
for (int i = 1; i < x; i++)
{
if (x % i == 0)
{
sum += i;
}
}
return sum;
}

int main()
{
for (int a = 2;; a++)
{
int b = fac_sum(a);
if (fac_sum(b) == a && a != b)
{
cout << a << " " << b << endl;
return 0;
}
}
return 0;
}

编程基础07
http://yjmanman.github.io/2024/09/25/07/
作者
YuJia
发布于
2024年9月25日
许可协议