Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program to find the prime factorization

Tags:

c

input

I wrote this code to find the prime factorization of a number. I just cannot figure out the last part. If x is entered as a double or float, the program should print an error message and terminate. How do I achieve this?

#include <stdio.h>

int main()
{
    int x, i;
    printf("Enter an integer:  ");
    scanf("%d", &x);
    
    if (x <= 1)
    {
        return 1;
    }
    printf("The prime factorization of %d is ", x);
    if (x > 1)
    {
        while (x % 2 == 0) 
        { 
            printf("2 "); 
            x = x / 2; 
        } 
        for (i = 3; i < 1009; i = i + 2)
        {
            while (x % i == 0) 
            { 
                printf("%d ", i); 
                x = x / i; 
            }
        }
    }
    return 0;
}
like image 789
Cade Dash Avatar asked Mar 16 '26 19:03

Cade Dash


1 Answers

Your starting point should cover all desired and undesired cases so you should take float number from a user, not int. Then, you should check whether whole decimal part of the number is 0. That is, if all of them equals 0, the user want to provide an int number instead of float.

First step is to declare a float number:

float y;

After, take its value from the user:

scanf("%f", &y);

Second step is to check whether it is int or float. There are many ways for this step. For example, I find roundf() function useful. It takes a float number and computes the nearest integer to this number. So if the nearest integer is the number itself then the number has to be int. Right?

if(roundf(y)!=y)

If you are sure it is an int, you can move onto the third step: convert float type to int type. It is called type-casting. This step is required for the remaining part of your program because in your algorithm you manipulate the number with int type so just convert it to int:

x = (int)y;

After adding the line above, you can use the rest of code which you typed. I give the whole program:

#include <stdio.h>
#include <math.h>
int main()
{
    int x,i;
    float y;
    printf("Enter an integer:  ");
    scanf("%f", &y);

    if(roundf(y)!=y){
        printf("%f is not an integer!",y);
        return 1;
    }

    else{
        x = (int)y;
    }

    if (x <= 1)
    {
        printf("%d <= 1",x);
        return 1;
    }

    else
    {
        printf("The prime factorization of %d is ", x);
        while (x%2 == 0)
        {
            printf("2 ");
            x = x / 2;
        }
        for ( i = 3; i < 1009; i = i + 2)
        {
            while (x%i == 0)
            {
                printf("%d ",i);
                x = x / i;
            }
        }
    }
    return 0;
}
like image 118
black Avatar answered Mar 18 '26 07:03

black