0

I've written a programm for college where I print out all prime number twins between two numbers. (f.e. between 1 and 12000)

In my printing statement i've written %04d for 4 digits. But what i want to do is to make this variable. (I tried %0%dd, but this didnt work.) I dont want to do write just the max digit count of int. I count hte digits of the int with int count = floor(log10(abs(b))) + 1;

Heres my complete code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int isPrime(int a);
void listOfPrimeNumberTwins(int a, int b);

typedef int twins[10000][2];

int main(){
    int a;
    int b;
    printf("Check if prime:\nEnter number: ");
    scanf(" %d", &a);
    b = isPrime(a);
    if (b == 0){
        printf("No Prime!");
    } else if (b == -1){
        printf("Negative number!");
    } else {
        printf("Prime!");
    }
    printf("\nPrime Number Twins:\nEnter number 1: ");
    scanf(" %d", &a);
    printf("Enter number 2: ");
    scanf(" %d", &b);
    listOfPrimeNumberTwins(a,b);
}
int isPrime(int a){
    int i;
    int b = 0;
    if (a == 1){
        return 0;
    }
    if (a <= 0){
        return -1;
    }
    for (i = 2; i < a; i++){
        if (a % i == 0){
            return 0;
        }
    }
    return 1;
}
void listOfPrimeNumberTwins(int a, int b){
    int count = floor(log10(abs(b))) + 1;
    int i;
    int j = 0;
    twins c;
    b -= 1;
    for (i = a; i < b; i++){
        if (i > 1 && isPrime(i) == 1 && isPrime(i + 2) == 1){
            c[j][0] = i;
            c[j][1] = i + 2;
            j += 1;
        }
    }
    if (j == 0){
        printf("No Prime number twins between %d and %d!", a,b);
    } else {
        printf("Prime number twins between %d and %d:\n", a,b);
        for (i = 0;i < j; i++){
            printf("%04d\t<-->\t%04d\n", c[i][0],c[i][1]);
        }
    }
}

How can I achieve what I want? Or is it just impossible like I want it?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Mr3m4r3
  • 55
  • 2
  • 10
  • 5
    likely duplicate of [printf string, variable length item](https://stackoverflow.com/questions/5932214/printf-string-variable-length-item) or [Set variable text column width in printf](https://stackoverflow.com/questions/7105890/set-variable-text-column-width-in-printf) or etc. – underscore_d Nov 16 '17 at 10:57
  • Please show an example ot the output you get vs. the output you want. I ran your program and the ouput looks ok to me. – Jabberwocky Nov 16 '17 at 11:01
  • 1
    Please see the [link](https://stackoverflow.com/questions/4133318/variable-sized-padding-in-printf). Please search before asking question. – MOE Nov 16 '17 at 11:06

0 Answers0