要求:设计一个程序,求出100-200间的所有素数,要求每行输出五个素数。判断一个数是否为素数用一个函数来实现。
C++实现:
#include<iostream>using namespace std;int judge(int m)//判断是否为素数{for (int n=2;n<m;n++) {if(m%n==0)return 0;}return 1;}int main(){int i,j,x;int isprime = 1;int count = 0;cout<<"输入一个数:"<<"\n";cin>>x;if(judge(x)==0)cout<<x<<"不是素数"<<"\n";else if(judge(x)==1) {cout<<x<<"是素数"<<"\n";}cout<<"100-200间的素数:"<<"\n";for (i = 100; i <= 200; i++) {for (j = 2; j < i; j++) {if (i % j == 0) {isprime = 0;break;}}if (isprime == 1) {cout<<i<<" ";count++;if (count % 5 == 0)cout<<"\n";}isprime = 1;}}
C语言实现:
#include<stdio.h>int judge(int m){for (int n=2;n<m;n++) {if(m%n==0)return 0;}return 1;}int main() {int i,j,x;int isprime = 1;int count = 0;printf("输入一个数:\n");scanf("%d",&x);if(judge(x)==0)printf("%d不是素数\n",x);else if(judge(x)==1) {printf("%d是素数\n", x);}printf("100-200间的素数:\n");for (i = 100; i <= 200; i++) {for (j = 2; j < i; j++) {if (i % j == 0) {isprime = 0;break;}}if (isprime == 1) {printf("%d ", i);count++;if (count % 5 == 0)printf("\n");}isprime = 1;}}
Java实现:
public class c_work2 {public static int xjudge(int m){for (int n=2;n<m;n++) {if(m%n==0)return 0;}return 1;}public static void main(String[] args){int i,j,x;int isprime = 1;int count = 0;System.out.println("输入一个数:");Scanner sc = new Scanner(System.in);x = sc.nextInt();if(xjudge(x) == 0)System.out.println(x+"不是素数");else if (xjudge(x) == 1)System.out.println(x+"是素数");System.out.println("100-200间的素数:");for (i = 100; i <= 200; i++) {for (j = 2; j < i; j++) {if (i % j == 0) {isprime = 0;break;}}if (isprime == 1) {System.out.print(i+" ");count++;if (count % 5 == 0)System.out.print("\n");}isprime = 1;}}}
运行结果: