【发布时间】:2018-01-04 13:32:25
【问题描述】:
我正在尝试解决这个代码战kata
基本上,我需要编写一个程序,该程序从特定范围(数字)中吐出一个 array/list 的数字,这些数字乘以 k primes。
countKprimes(5, 500, 600) --> [500, 520, 552, 567, 588, 592, 594]
现在我的程序“工作”了,因为它可以正确打印结果,但如果我把它放在 codewars 的答案区域(当然没有main),它就会永远运行。
“错误代码SIGKILL:进程已终止。完成时间超过12000毫秒”
这是代码战模板
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// In the preloaded section are some functions that can help.
// They can be used as a small library.
// There is no file to include, only the templates below.
struct node {
int data;
struct node *next;
};
struct list {
size_t sz;
struct node *head;
};
struct list* createList();
// push data at the head of the list
void insertFirst(struct list* l, int data);
struct list* reverse(struct list* l);
void listFree(struct list* l);
// functions to write
struct list* kPrimes(int k, int start, int nd)
{
// your code
}
这是我的代码
#include <stdio.h>
struct list{
int a[600];
};
int smallestPrimeFactor(int number){
int x;
for(x = 2; x < number; x++) {
if(number % x == 0) {
return x;
}
}
return number;
}
int primefactors(int ofnumber){
static int counter = 0;
int tempcounter = counter;
int nextnumber = ofnumber/smallestPrimeFactor(ofnumber);
if(nextnumber != 1) {
if(ofnumber >= nextnumber) {
counter++;
primefactors(nextnumber);
}
}
return (counter - tempcounter) + 1;
}
struct list kPrimes(int k, int start, int nd){
int x, g = 0;
struct list ls;
for(x = start; x < nd; x++){
if(primefactors(x) == k){
ls.a[g] = x;
g++;
}
}
return ls;
}
int main(int argc, int **argv){
int p = 5, s = 500, e = 600;
int j = 0;
while(kPrimes(p, s, e).a[j] != '\0'){
printf("%d\n", kPrimes(p, s, e).a[j]);
j++;
}
}
我认为这里的罪魁祸首是
struct list{
int a[600];
};
也许在读取数组时,测试文件超出了 a 的索引,超过了 '\0'。
我想到了一种解决方法,将 a 设为一个指向整数的指针,但 int *a; 不会打印任何内容。
我知道返回数组的方法不止一种。使用引用,使用静态数组,将数组作为参数传递等。但我想解决这个代码战的方式。认为这将是一次很好的学习体验。
那么,我应该如何使用
struct node {
int data;
struct node *next;
};
struct list {
size_t sz;
struct node *head;
};
解决问题?
【问题讨论】:
-
你不应该关心结构本身,你应该使用
createList()、insertFirst()、reverse等。