C#编程题分享(5)

判断质数问题

输⼊⼀个正整数,判断该数是否是质数。如果为质数输出 yes,如果不是输出no

样例输⼊113 输出yes

cs 复制代码
int n = Convert.ToInt32(Console.ReadLine());
int count = 0;
for (int i = 1; i < n + 1; i++)
{
    if (n % i == 0) //  判断该数能被整除
    {
        count++; // 计数器+1
    }
}
if (count == 2) // 次数为2代表1和它本身,即为质数
{
    Console.WriteLine("yes");
}
else
{
    Console.WriteLine("no");
}

输出因数问题

输⼊⼀个整数,输出该整数的因数个数和所有因数。

样例输⼊ 9 样例输出 3 1 3 9

cs 复制代码
int n = Convert.ToInt32(Console.ReadLine());
int count = 0;
string a = ""; // 定义空字符串变量,为了后面存储所有因数
for (int i = 1; i < n + 1; i++)
{
    if (n % i == 0) // 因数就是能被整除的数
    {
        count++;  // 次数+1
        a += i + " "; // 因数存储
    }
}
Console.WriteLine(count); // 输出因数个数
Console.Write(a); // 输出所有的因数

整数插入有序数组组成新的有序数组:

有n(n<=100)个整数,已经按照从⼩到⼤顺序排列好,现在另外给⼀个整数x,请将该数插⼊到序列中,并使新的序列仍然有序。输出新的序列。

样例输入:10 20 30 40 50 15 样例输出:10 15 20 30 40 50

cs 复制代码
class Program
    {
        static void Main(string[] args)
        {
            string str = Console.ReadLine();// 输入有序数组
            // 将字符数组转换为整数数组
            string[] strArray = str.Split(' ');
            int[] intArray = new int[strArray.Length];
            for (int i = 0; i < strArray.Length; i++)
            {
                int num = Convert.ToInt32(strArray[i]);
                intArray[i] = num; // 赋值
            }

            // 给的整数x
            int x = Convert.ToInt32(Console.ReadLine());

            int nIndex = intArray.Length - 1;// 假设索引是最后一位
            for (int i = 0; i < intArray.Length - 1; i++)
            {
                if (x >= intArray[i] && x <= intArray[i + 1]) // 找出该整数的索引
                {
                    nIndex = i;
                    break;
                }
            }

            if (x < intArray[0]) // 特殊情况,该整数为最小值时
            {
                nIndex = -1;
            }

            int[] intNewArray = new int[intArray.Length + 1]; // 定义新数组

            // 0-nIndex = 0 - -1
            for (int i = 0; i < nIndex + 1; i++)
            {
                intNewArray[i] = intArray[i]; // 遍历到nIndex + 1给新数组赋值
            }

            intNewArray[nIndex + 1] = x; // 将该整数也放入新数组中
            // nIndex+1 -- length-1
            for (int i = nIndex + 1; i < intArray.Length; i++)
            {
                intNewArray[i + 1] = intArray[i];  // 从nIndex + 1开始继续遍历给新数组赋剩余的值
            }

            foreach (int num in intNewArray)
            {
                Console.Write(num + " ");// 输出新的有序数组
            }
        }
    }
相关推荐
用户67570498850213 分钟前
Go 语言中如何操作二维码?
后端
这里有鱼汤15 分钟前
想成为下一个吉姆·西蒙斯,这十种经典K线形态你一定要记住
后端·python
SimonKing20 分钟前
吊打面试官系列:BeanFactory和FactoryBean的区别
java·后端·面试
Scoful23 分钟前
快速用 uv 模拟发布一个 Python 依赖包到 TestPyPI 上,以及常用命令
开发语言·python·uv
江湖十年29 分钟前
一行命令统计代码行数
后端·go·命令行
天天摸鱼的java工程师32 分钟前
互联网行业能力解刨:从Java后端八年开发经验看
前端·后端·程序员
brzhang39 分钟前
Android 16 卫星连接 API 来了,带你写出「永不失联」的应用
前端·后端·架构
程序员爱钓鱼1 小时前
Go并发模型与模式:context 上下文控制
后端·google·go
clock的时钟1 小时前
c++第七天--继承与派生
开发语言·c++
AI小智1 小时前
AI提效99.5%!英国政府联手 Gemini,破解城市规划审批困局
后端