写一段go语言求1到100的素数
时间: 2023-03-14 09:12:47 浏览: 80
package mainimport "fmt"func main(){
var primeCount int
for i := 2; i <= 100; i++ {
for j := 2; j < i; j++ {
if i % j == 0 {
break
}
if j == i-1 {
fmt.Printf("%d\t", i)
primeCount++
}
}
}
fmt.Printf("\n一共有%d个素数", primeCount)
}
相关问题
写一段c语言代码求1到100的素数
#include <stdio.h>
int main()
{
int i, j, flag;
printf("以下是1到100之间的素数:\n");
for(i=2; i<=100; i++)
{
flag = 0;
for(j=2; j<=i/2; j++)
{
if(i%j == 0)
{
flag = 1;
break;
}
}
if(flag == 0)
{
printf("%d ",i);
}
}
return 0;
}
请写一个求1到100间素数的c++代码
### 回答1:
好的,这是一个求1到100间素数的C代码:
```
#include <stdio.h>
#include <math.h>
int main() {
int i, j;
for (i = 2; i <= 100; i++) {
int is_prime = 1;
for (j = 2; j <= sqrt(i); j++) {
if (i % j == 0) {
is_prime = 0;
break;
}
}
if (is_prime) {
printf("%d\n", i);
}
}
return 0;
}
```
希望对您有所帮助!
### 回答2:
以下是一个求1到100间素数的C代码:
```c
#include<stdio.h>
int isPrime(int num){
if(num <= 1){
return 0;
}
for(int i = 2; i <= num/2; i++){
if(num % i == 0){
return 0;
}
}
return 1;
}
int main(){
printf("1到100间的素数有:\n");
for(int i = 2; i <= 100; i++){
if(isPrime(i)){
printf("%d ", i);
}
}
return 0;
}
```
代码中定义了一个函数`isPrime`,用于判断一个数是否为素数。如果一个数小于等于1,则不是素数。否则,从2开始到该数的一半遍历,若存在可以整除的数,则不是素数,返回0;否则是素数,返回1。
在`main`函数中,使用循环从2到100遍历,对每个数字调用`isPrime`函数进行判断。如果为素数,则输出该数字。
运行上述代码,会输出1到100间的所有素数。
### 回答3:
以下是求1到100间素数的C代码:
```c
#include <stdio.h>
int isPrime(int n) {
if(n <= 1) {
return 0;
}
for(int i = 2; i <= n/2; i++) {
if(n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
printf("1到100间的素数有:\n");
for(int i = 1; i <= 100; i++) {
if(isPrime(i)) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
```
在上面的代码中,我们首先定义了一个名为`isPrime`的函数,用于判断一个数是否为素数。该函数会返回0(假)和1(真)两个值,判断依据是该数是否能被2到n/2之间的任意整数整除。如果存在能整除的数,则返回0,否则返回1。
然后在`main`函数中,从1到100进行遍历,对于每个数调用`isPrime`函数进行判断。如果返回值为1,即该数为素数,则打印出该数。
最终的输出结果为:
```
1到100间的素数有:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![asm](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)