c:java
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
unsigned long *p = NULL;
unsigned long t = 0L;
bool found = false;
size_t total = 0;
size_t count = 0;
int i = 0;
printf("要多少質數(最少4個)? ");
scanf(" %d",&total);
total = total<4U ? 4U : total;
p = (unsigned long *)malloc(total* sizeof(unsigned long));
if(p == NULL){
printf("內存不足\n");
return 1;
}
*p = 2UL;
*(p+1) = 3UL;
*(p+2) = 5UL;
count = 3U;
t = 5U;
while(count < total){
t += 2UL;
for(i = 0;i<count;i++){
if(!(found = (t % *(p+i)))){
break;
}
}
if(found){
*(p+count++) = t;
}
}
for(i = 0;i<total; i++){
if(!(i%5U)){
printf("\n");
}
printf(" %lu ",*(p+i));
}
printf("\n");
system("pause");
return 0;
}
ide
----------------------------------------------------------------------------------------------------------------------------------------------------------------spa
java:內存
package com.test;
import java.util.ArrayList;
import java.util.List;
/**
* 求質數
* @author
*
*/
public class Test1 {
public static List<Integer> get(int num){
List<Integer> lst = new ArrayList<Integer>();
lst.add(2);lst.add(3);lst.add(5);
int item = 5;
while(num > lst.size()){
item += 2;
for(int i = 0;i<lst.size();i++){
int a = lst.get(i);
if(item%a == 0){
break;
}
if(i == lst.size()-1){
lst.add(item);
}
}
}
return lst;
}
public static void main(String[] args) {
List<Integer> lst = get(1000);
System.out.println(lst.get(999));
int index = 0;
for(int i = 0;i<lst.size();i++){
index ++;
if(index == 5){
index =0;
}
}
}
}
get