XXX-笔试 偶数间的距离

本文介绍了一个计算任意两个偶数间质数数量的C++程序。该程序通过输入一组偶数,计算并输出每两个相邻偶数之间的质数数量之和。使用了质数判断函数和质数计数函数。

定义两个偶数间的质数的个数为两个偶数的距离


输入一组偶数,求出任意两个偶数间距离之和



#include<iostream>
#include <cmath>
#include<algorithm>
using namespace std;

#define N 10000
int a[N]={0};
int b[N]={0};
bool isPrime(int n)
{
    if(n < 2) return false;

    for(int i = 2; i<=sqrt(n); ++i)
        if(n%i == 0) return false;

    return true;
}

int countPrime(int from,int to){
	int count=0;
	for(int i=from+1;i<to;i++)
		if(isPrime(i))
			count++;
	return count;
}
int main(){
	int n;
	while(cin>>n){
		int i=0,j=0;
		int reslut=0;
		for(i=0;i<n;i++)
			cin>>a[i];
		//sort(a,a+n);
		for(i=0;i<n-1;i++)
        {
            b[i]=countPrime(a[i],a[i+1]);
        }
        for(i=0;i<n-1;i++)
        {
            reslut+=b[i];
            for(j=i+1;j<n-1;j++)
            {
                reslut+=b[j];
            }
        }
	cout<<reslut<<endl;
	}
	return 0;
}


在Unity中处理字符串提取操作时,可以使用C#内置的字符串处理方法,例如`Substring`、`Split`或正则表达式(`System.Text.RegularExpressions.Regex`)。对于格式固定的字符串,例如 `"SKU-xx-xxx-xxx-yy-yyyyy"`,可以通过索引和长度计算提取中部分 `"xx-xxx-xxx"`。 ### 使用 `Substring` 和 `IndexOf` 如果字符串格式固定,可以结合`IndexOf`方法找到特定分隔符的位置,再使用`Substring`提取目标子字符串。示例代码如下: ```csharp string input = "SKU-xx-xxx-xxx-yy-yyyyy"; int firstDash = input.IndexOf('-'); // 第一个'-'的位置 int secondDash = input.IndexOf('-', firstDash + 1); // 第二个'-'的位置 int fourthDash = input.IndexOf('-', input.IndexOf('-', secondDash + 1) + 1); // 第四个'-'的位置 string result = input.Substring(secondDash + 1, fourthDash - secondDash - 1); Debug.Log(result); // 输出: xx-xxx-xxx ``` ### 使用正则表达式 如果字符串模式可能存在变化,但整体结构保持一致,可以使用正则表达式匹配目标部分。以下示例通过正则表达式提取所需子字符串: ```csharp using System.Text.RegularExpressions; string input = "SKU-xx-xxx-xxx-yy-yyyyy"; Regex regex = new Regex(@"SKU-(.*?)-yy-yyyyy"); Match match = regex.Match(input); if (match.Success) { string result = match.Groups[1].Value; Debug.Log(result); // 输出: xx-xxx-xxx } ``` ### 使用 `Split` 方法 将字符串按特定字符分割成数组,然后组合所需部分。适用于分隔符固定且位置明确的情况: ```csharp string input = "SKU-xx-xxx-xxx-yy-yyyyy"; string[] parts = input.Split('-'); string result = $"{parts[1]}-{parts[2]}-{parts[3]}"; Debug.Log(result); // 输出: xx-xxx-xxx ``` 以上方法均适用于Unity开发中的C#脚本编写,具体选择哪种方式取决于实际需求和字符串的灵活性。若格式固定,推荐使用`Substring`或`Split`;若格式存在变体,建议使用正则表达式进行更灵活的匹配。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值