matlab cody学习笔记 day12

(1)The Goldbach Conjecture
The Goldbach conjecture asserts that every even integer greater than 2 can be expressed as the sum of two primes.
Given the even integer n, return primes p1 and p2 that satisfy the condition n = p1 + p2. Note that the primes are not always unique. The test is not sensitive to order or uniqueness. You just need to meet the appropriate conditions.
Example:
Input n = 286
Output (any of the following is acceptable)
[ 3 283]
[283 3]
[ 5 281]
[107 179]
[137 149]
哥德巴赫猜想,寻找一个大于2的偶数是由哪两个素数组成的。
isprime函数,判断是否为素数。
答:
function [p1,p2] = goldbach(n)
for i = 1:n-1
if(isprime(i)==1)
if(isprime(n-i)==1)
p1=i;
p2=n-i;
else
continue;
end
end
end
end
(2)Bullseye Matrix
Given n (always odd), return output a that has concentric rings of the numbers 1 through (n+1)/2 around the center point. Examples:
Input n = 3
Output a is [ 2 2 2
2 1 2
2 2 2 ]

Input n = 5
Output a is [ 3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3 ]
如何生成一个靶心矩阵。
答:
function a = bullseye(n)
a = ceil(sqrt(spiral(n))/2+0.5); %spiral(n)命令生成n维从1开始的顺时针螺旋矩阵
end
答:
function a = bullseye(n)
a=toeplitz(1:n); %生成1到n的托普利兹矩阵(T型矩阵)
a=(a+rot90(a))/2; %rot90()逆时针旋转矩阵
end

(3)Check if sorted
Check if sorted.
Example:
Input x = [1 2 0]
Output y is 0
用昨天的sort函数进行排序再进行判断。
答:
function y = sortok(x)
x1 = sort(x);
x2 = sort(x,‘descend’);
if x == x1
y = 1;
elseif x == x2
y =1;
else
y =0;
end
end

猜你喜欢

转载自blog.csdn.net/yxnooo1/article/details/114007721