用c编写一个程序,在出现非素数后跳过2个元素

问题描述 投票:0回答:1

我根据我的知识编写了代码,但我没有得到正确的输出。我在下面提供了我的代码

#include <stdio.h>

int main() {
    int i, j, isPrime, n, a[1000], k;

    // Input array limit
    printf("Enter array limit: ");
    scanf("%d", &n);

    // Input array elements
    printf("Enter array elements:\n");
    for(i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }

    // Loop through the array
    for(i = 0; i < n;  i++;) {
        // Check if current element is prime
        if (a[i] < 2) {
            isPrime = 0; // Numbers less than 2 are not prime
        } else {
            isPrime = 1; // Assume the number is prime
            for (j = 2; j * j <= a[i]; j++) {
                if (a[i] % j == 0) {
                    isPrime = 0; // Found a divisor, not a prime number
                    break;
                }
            }
        }

        // Print the current number based on prime status
        if (isPrime) {
            printf("%d ", a[i]);
        } else {
            printf("%d ", a[i]);
            // Skip the next two elements by shifting the array
            for (k = i + 1; k < n - 2; k++) {
                a[k] = a[k + 2];
            }
            n -= 2; // Reduce array size by 2
            i--; // Recheck the current position
        }
      
    }

    return 0;
}

当我运行此代码时,我没有得到正确的输出。 例如:- 如果我输入 array limit 9 并打印 1-9 我得到的输出为 1 1 1 1 1 。 你能帮我解决这个问题吗

我想要解决我的问题。

arrays c primes delete-operator
1个回答
0
投票

试试这个

#include <stdio.h>

int is_prime(int num) {
    if (num < 2) return 0;
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) return 0;
    }
    return 1;
}

int main() {
    int i, n, a[1000];

    // Input array limit
    printf("Enter array limit: ");
    scanf("%d", &n);

    // Input array elements
    printf("Enter array elements:\n");
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }

    // Loop through the array
    for (i = 0; i < n; ) {
        // Check if current element is prime
        if (!is_prime(a[i])) {
            // Print the current non-prime number
            printf("%d ", a[i]);

            // Skip the next two elements
            i += 3;
        } else {
            // Print the current prime number
            printf("%d ", a[i]);
            i++;
        }
    }

    return 0;
}

© www.soinside.com 2019 - 2024. All rights reserved.