当前位置: 首页 > news >正文

C#编程题分享(5)

 判断质数问题

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

样例输⼊113 输出yes

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

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

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

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

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

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; // 赋值}// 给的整数xint 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 - -1for (int i = 0; i < nIndex + 1; i++){intNewArray[i] = intArray[i]; // 遍历到nIndex + 1给新数组赋值}intNewArray[nIndex + 1] = x; // 将该整数也放入新数组中// nIndex+1 -- length-1for (int i = nIndex + 1; i < intArray.Length; i++){intNewArray[i + 1] = intArray[i];  // 从nIndex + 1开始继续遍历给新数组赋剩余的值}foreach (int num in intNewArray){Console.Write(num + " ");// 输出新的有序数组}}}

http://www.lryc.cn/news/251279.html

相关文章:

  • 群晖Video Station 添加海报墙-新方法
  • 【MODBUS】Modbus协议入门简介
  • ORA-00257: archiver error. Connect internal only, until freed……
  • 继承 和 多肽(超重点 ! ! !)
  • H265、VP9、AV1视频编码器性能对比
  • C语言-结构体
  • C#拼夕夕自动化登录,电商网页自动化操作。WebView2
  • 【Spring Boot 源码学习】BootstrapRegistryInitializer 详解
  • 预览功能实现
  • canvas基础:绘制贝塞尔曲线
  • 高项备考葵花宝典-项目范围管理输入、输出、工具和技术
  • 在表格中显示字典的内容(根据后端返回的数据)vue3
  • 编程怎么学才能快速入门,分享一款中文编程工具快速学习编程思路,中文编程工具之边条主控菜单构件简介
  • MySQL索引下推
  • 代码随想录刷题题Day3
  • GO学习之 单例模式 sync.Once
  • 应用安全四十三:无密码认证安全
  • Lattice-Based Blind Signatures: Short, Efficient, and Round-Optimal
  • Qt/C++音视频开发57-切换音视频轨道/切换节目流/分别切换音频视频轨道
  • 深度学习之基于Django文本情感分析识别系统
  • 138. 随机链表的复制 --力扣 --JAVA
  • Python Flask 框架开发
  • k8s安装-学习环境
  • Vue3动态表单
  • 2312skia,15vulkan及技巧
  • TLSF算法概念,原理,内存碎片问题分析
  • sharding-jdbc实现分库分表
  • JDK中lock锁的机制,其底层是一种无锁的架构实现的,公平锁和非公平锁
  • c++通过serial库进行上下位机通信
  • 【傻瓜级JS-DLL-WINCC-PLC交互】7.​C#直连PLC并读取PLC数据