User forums > Help

Begginer problem

(1/1)

Blo:
I have a questions regarding this problem:
Write a program that loads the natural number n. It should be checked whether the number x = k*k - 79k + 1601 , k ≥ 0, prime or not, for all natural numbers k ≤ n. The program should print the numbers k and x (for its k), the answer to the question and, if the number x (for its k) is not prime, print its smallest prime factor.

Everything is good until I check for number 80+. For some reason is stops at 79. Is there any reason why? I would appreciate the answer. And if you want, give me some suggestions to improve this program (I just started learning C program).
I am only using stdio.h file. Want to learn as much as I can with this one and then move on to more.


#include <stdio.h>
int main(void){

    int n, x, k = 1, prime = 0;
    int i, j, min_prime_fact;

    printf("n: ");
    scanf("%d", &n);

    for(x = k * k - 79 * k + 1601; k <= n; ++k){
         x = k * k - 79 * k + 1601;
         for(i = 2; i <= x / 2; ++i){
            if(x % i == 0){
                prime = 1;
            }
         }
         if(prime == 0){
            printf("For %d number %d is prime.\n", k, x);
         } else {
                do {
                    min_prime_fact = x / 2;
                    for(j = 2; j <= x / 2; ++j){
                        if(x % j == 0){
                            if(j < min_prime_fact){
                                min_prime_fact = j;
                            }
                            x = x / j;
                        }
                    }
                } while(x > 1);
                printf("For %d number %d is not prime. %d is its smallest prime factor.\n", k, x, min_prime_fact);
        }
    }

    return 0;
}

Miguel Gimenez:
General programming is off-topic here.

jordi:

--- Code: ---#include <stdio.h>
#include <stdbool.h>

bool isPrime(int x)
{
    bool prime = true;
    for (int i = 2; i <= x/2; ++i)
    {
        if (x % i == 0)
        {
            prime = false;
            break;
        }
    }
    return prime;
}

int main(void){

    int n;
    printf("n: ");
    scanf("%d", &n);

    for(int k = 1; k <= n; ++k){
        int x = k * k - 79 * k + 1601;
        if(isPrime(x)){
            printf("For %d number %d is prime.\n", k, x);
        } else {
            int min_prime_fact = 0;
            for(int j = 2; j <= x / 2; ++j){
                if(x % j == 0){ /* check j for factor of x */
                    if(isPrime(j)){
                        min_prime_fact = j;
                        break;
                    }
                }
            }
            printf("For %d number %d is not prime. %d is its smallest prime factor.\n", k, x, min_prime_fact);
        }
    }

    return 0;
}

--- End code ---

Navigation

[0] Message Index

Go to full version