Goldbach theory in C - c

I want to write some code which takes any positive, even number (greater than 2) and gives me the smallest pair of primes that sum up to this number.
I need this program to handle any integer up to 9 digits long.
My aim is to make something that looks like this:
Please enter a positive even integer ( greater than 2 ) :
10
The first primes adding : 3+7=10.
Please enter a positive even integer ( greater than 2 ) :
160
The first primes adding : 3+157=160.
Please enter a positive even integer ( greater than 2 ) :
18456
The first primes adding : 5+18451=18456.
I don't want to use any library besides stdio.h. I don't want to use arrays, strings, or anything besides for the most basic toolbox: scanf, printf, for, while, do-while, if, else if, break, continue, and the basic operators (<,>, ==, =+, !=, %, *, /, etc...).
Please no other functions especially is_prime.
I know how to limit the input to my needs so that it loops until given a valid entry.
So now I'm trying to figure out the algorithm.
I thought of starting a while loop like something like this:
#include <stdio.h>
long first, second, sum, goldbach, min;
long a,b,i,k; //indices
int main (){
while (1){
printf("Please enter a positive integer :\n");
scanf("%ld",&goldbach);
if ((goldbach>2)&&((goldbach%2)==0)) break;
else printf("Wrong input, ");
}
while (sum!=goldbach){
for (a=3;a<goldbach;a=(a+2))
for (i=2;(goldbach-a)%i;i++)
first = a;
for (b=5;b<goldbach;b=(b+2))
for (k=2;(goldbach-b)%k;k++)
sum = first + second;
}
}

Have a function to test primality
int is_prime(unsigned long n)
And then you only need to test whether a and goldbach - a are both prime. You can of course assume a <= goldbach/2.
And be sure to handle goldbach = 4 correctly.
If the requirements don't allow defining and using your own functions, ignore them first. Solve the problem using any functions you deem helpful and convenient. When you have a working solution using disallowed functionality, then you start replacing that with allowed constructs. Self-defined functions can be inlined directly, replacing the return with an assignment, so instead of if (is_prime(a)), you have the code to determine whether a is prime and instead of returning the result you assign it is_prime = result; and test that variable if (is_prime). Where you have used library functions, reimplement them yourself - efficiency doesn't matter much - and then inline them too.

Related

How to write a code that will count the number of prime digits that consists only of prime numbers

First, I need to input N.
For example, from 1 to 5, there is 3 prime number: 2,3,5.
Now, I need to find prime numbers that consists only from odd numbers.
53 is it's example.
It's always easier to think about code like this if you partition different functionality off into different functions. You can, theoretically, interweave all the code together, to have code that's checking for prime numbers and odd digits at the same time, but it's much harder to write, read, understand, and debug, so unless there's some compelling reason to compress everything (like, maybe, efficiency), for everyday purposes it's much easier to keep things separate.
So although you haven't quite written your code that way yet, what I'm imagining is that we have a number n we're interested in checking. In your case it's the loop variable in your for(i = 2; i <= N; i++) loop. If you were just counting primes, you'd have
if(isprime(n))
count++;
Here I'm imagining that you have a separate function called isprime() that you can call to see if a number is prime. (It would contain the same kind of code you currently have for setting your isPrime variable to true or false.) And then, if you want to count how many of the prime numbers have only odd digits, you might go to something like this:
if(isprime(n)) {
count++;
if(has_only_odd_digits(n))
count2++;
}
Arranged this way, count will be the count of how many numbers were prime, and count2 will be the count of how many numbers were prime and had only odd digits. (Different arrangements are obviously possible to answer different variants of the question, like how many numbers had only odd digits, whether or not they were prime.)
And then the obvious question is: Where does the hypothetical has_only_odd_digits function come from? We'll have to write it ourselves, of course, but the nice thing is that while we're writing it, we'll only have to think about the problem of determining whether digits are even or odd; we won't have to worry about prime numbers at all.
So let's take a first cut at writing has_only_odd_digits. You had a version, sort of, in the code you originally posted:
int has_only_odd_digits(int n)
{
if(n % 2 == 0) /* if even */
return 0;
else return 1;
}
But this is wrong: it just tests whether the number n itself is even or odd. It will return "false" for 2 and 20 and 222, and it will return "true" for 3 and 13 and 13579, but it will also return "true" for 2461, since 2461 is odd, even though it happens to have mostly even digits. So for a working version of has_only_odd_digits we need something more like this:
int has_only_odd_digits(int n)
{
for(each digit d of n) {
if(d % 2 == 0)
return 0;
}
return 1;
}
This is pseudocode, not real C code yet. Notice that this time there's no else in the if statement. If we find an even digit, we're done. But if we find an odd digit, we can't necessarily return "true" yet — we have to check all the digits, and only return true" if none of the digits were even.
But the real question is, how do we get at those digits? An int variable is not represented internally by anything remotely like an array of its decimal digits. No, an int variable is an integer, a number, and the only way to get at its decimal-digit representation is to, literally, divide it repeatedly by 10.
So, fleshing out our code just a little bit more, we're going to have something like
int has_only_odd_digits(int n)
{
while(n != 0) {
int d = one digit of n;
if(d % 2 == 0)
return 0;
n = the rest of n, except for the digit d we just checked;
}
return 1;
}
And that's as far as I'm going to take it: I think you've got the idea by now, and in case this is a homework assignment, I'm not going to do all the work for you. :-) I'll note that there's also still a discrepancy to nail down between your question title and your problem description in the question: are you looking for prime numbers with odd digits, or prime digits? (And if the latter, I'm honestly not sure what to do with 1's, but that'll be a question for you and your instructor, I guess.)
But, in closing, I want to point out a couple of things: besides learning how to count primes with odd digits, I hope you've also also begun to appreciated two, much more general, related points:
If you break a complicated program up into separate functions, it's much easier to think about each function (each part of the problem) in isolation.
If you're not sure how to do something, often you can attack it in little steps, sort of a "successive refinement" approach, like I did with the several different versions of the has_only_odd_digits function here.
Now, it's true, you can't necessarily just break a complicated problem up into functions any old way, and when you're solving a problem by stepwise refinement, you have to choose the right steps. But, still, these are definitely valuable approaches, and with time and experience, you'll find it easier and easier to see how to break a big problem down into pieces you can handle.

How do I generate random numbers but not repeating and within a certain range based on user input?

Currently, I am experimenting some codes regarding/about random numbers. The problem is, when I run the program, input any number (ex. 12), I, sometimes get the correct and sometimes wrong answer. The correct answer must be any non repeating random numbers based on user input. (ex. input 5, output must be 1. seats[12]=1, 2. seats[19]=1,..., 5. seats[47]=1). I do not know what to do and yeah help me coders!
Here's the code:
#include<stdio.h>
#include<conio.h>
#include<time.h>
main()
{
int x,y,chc1A,seats[50]={};
printf("Enter a number: ");
scanf("%d",&chc1A);
srand(NULL);
for(x=0;x<chc1A;x++)
{
if(seats[rand()%50]==0)
seats[rand()%50]=1;
else
x--;
}
for(x=0,y=1;x<50;x++)
if(seats[x]==1)
{
printf("%d. seats[%d] = %d\n",y,x,seats[x]);
y++;
}
getch();
}
I do not really know what's wrong please enlighten me.
I run and coded this on Dev C++
What I want to do is: generate random numbers between 0-49 and putting it in an array seats[50]. (ex 38 then put 1 in array seats[38]). Btw this code represents passengers sitting on a bus with 50 seats. So the "1" means that the seat is occupied.
This part may cause problem.
for(x=0;x<chc1A;x++)
{
if(seats[rand()%50]==0)
seats[rand()%50]=1;
else
x--;
}
I think by
if(seats[rand()%50]==0)
seats[rand()%50]=1;
you meant to generate a random number, use that as index to seats and if seats[random_no] is 0, set seats[random_no] to 1.
But the random number in the if statement and the one in its body are different numbers.
You could use
int index = rand()%50;
if(seats[index]==0)
seats[index]=1;
Consider changing the signature of your main() function. See What are the valid signatures for C's main() function?
conio.h is not part of the standard, try to avoid its usage. Same goes for getch() as it's from conio.h.
srand() expects an unsigned int as argument and NULL is not of that type. See here.
Include stdlib.h to use srand().
And checking the return value of scanf() is a good idea. You can see if it failed or not.

Converting a result of Integer to String or Word in C

so i have a problem here. I am working on my class assignment which is create a calculator but every result must be in a word, example :
int a,b,c;
printf("Input first number:");
scanf("%d", &a);
printf("Input second number:"):
scanf("%d", &b);
c=a+b;
printf("The result are: %d", c);
printf("If in words, it is = ");
switch(c){
case 0:printf("abcdef");break;
case 1:printf("bc");break;
case 2:printf("abged");break;
case 3:printf("abgcd");break;
case 4:printf("fbgc");break;
case 5:printf("afgod");break;
case 6:printf("fgcde");break;
case 7:printf("abc");break;
case 8:printf("abcdefg");break;
case 9:printf("abcdfg");break;
default :printf("error");break;
So the result from this when im running it is :
Input first number : 12
input second number : 12
The result are: 24
If in words, it is = error
so what I'm confused here is how I did print the c result as a word? so what i want from my output is
Input first number : 12
input second number : 12
The result are : 24
If in words, it is = abged fbcg
so far I'm searching for answers but I cannot find it. If anyone here can help me, please do.
Thanks in advance
*edited
what i want from my output is
Input first number : 12
input second number : 12
The result are : 24
If in words, it is = abged fbcg
The question would be much clearer if you had written "two four" instead of "abged fbcg"...
You apparently want to print the "tens" and the "ones" separately. (Probably the "hundreds" as well.)
As this is a homework assignment, I will only give you some hints instead of a complete solution:
If you divide c by 10, you get the "tens". If you divide that result by 10 again, you get the "hundreds".
If something like "two four" would be acceptable, you can use the same lookup for "tens" and "ones". If you actually need "twenty four", you need a lookup for "tens" and a different one for "ones".
You need to print the words for the highest-order (leftmost) digit first, but you get it last from the by-10 divisions I mentioned above. So you need to "store" the lookup result for "ones" somewhere while you do the lookup for "tens" (and, perhaps, "hundreds"). Storage could be...
...an array. Be careful to check the numbers entered against the space in the array (so you don't overflow if someone enters too-large numbers). If you do it right, you do not need to store the strings you looked up, as you could store pointers to those strings.
...a recursive function. (One that calls itself with the value divided by 10, then does the lookup for the "ones" of the value it was called with -- you get that via the modulo operator, c % 10.)
The first problem here, you missed to use the break statement after each case statement.
Hence, yours is a fall-through switch case, which is not what you want. It will jump to the case matching in switch statement and then fall-thorough all other available case statements.
Once you have solved that problem, one of the possible the approach to target the next problem is to explain it properly, with the current description, it's not very clear.
Use a lookup for all the options of this word and then print the relevant according to the index without all the switch case mess
char* lookup = {
{"abcdef\n"},
{"bc\n"},
{"abged\n"},
{"abgcd\n"},
{"fbgc\n"},
{"afgod\n"},
{"fgcde\n"},
{"abc\n"},
{"abcdefg\n"},
{"abcdfg\n"},
};
then==>
c=a+b;
if (c>9)
{
printf("error\n");
}
else
{
printf(lookup[c]);
}
ok, so you mean you want to print a string for each digit of a number, which is the result of whatever math function?
Try [untested]
int d = c;
do {
switch (d % 10) { /* your replacement-text-switch goes here */ }
d /= 10;
} while (d != 0)
This will print out the number in reverse.
If you want to print it out the other way, then you have to know about the maximum number you are going to calculate. (Or, being advanced you can use logarithm to determine the length of a number.)

Variable length arithmetic calculator WITHOUT using strings?

I'm trying to create a calculator that solves arithmetic expressions of different lengths (e.g. 2+3/4 or 7*8/2+12-14), and I was wondering if it was possible to do so without the use of strings.
I've found countless tutorials explaining how to make a simple calculator with only two numbers and an operator, and I've also found examples using sscanf and strings to get the input.
However, my question is: Is there a way (is it even possible) to get variable length inputs without using strings?
At first I thought i could simply add more specifiers:
int num1 , num2, num3;
char op1, op2;
printf("Please enter your equation to evaluate: ");
scanf("%d%c%d%c%d", &num1, &op1, &num2, &op2, &num3);
but obviously, that doesn't work for equations longer than 3 numbers or less than 3 numbers.
I was also thinking of perhaps using some sort of recursive function, but I'm not sure how I would do that if I need to ask for the entire equation up front?
If you intend to read ASCII from user input, or from command line arguments, then you're pretty inescapably in the world of strings. What you can do is convert them into something else as early as possible.
You could abandon ASCII altogether and define a binary file format.
For example, you might say that each pair of two bytes is a token. The first byte is an element type ( signed integer, unsigned integer, float, operator), the second byte is the value.
Pseudocode:
while(!done) {
int type = read(f);
int value = read(f);
switch(type) {
case TYPE_INTEGER:
push_to_stack(value);
break;
case TYPE_FLOAT:
push_to_stack_as_float(value);
break;
case TYPE_OPERATOR:
execute_operator(value);
break;
}
}
Quite why you would force yourself down this route, I don't know. You'd probably find yourself wanting to write a program to convert ASCII input into your binary file format; which would use strings. So why did you run away from strings in the first place?
you can create a list of struct, every struct will have to contains a value OR a sub list, an operator (char?) and a reference to the next (and or before) char.
Then you just ask the user for a number (or "("/")"), and a operator sign. Every number + operator is a new element in list, every ( is a sub list, every ) is a return to superior list (you can even don't create a sublist, but elaborate it on the fly and return just the result, like a recursive function)
Also struct and code can be elaborated to support multiple parameter.

codechef :wrong answer error in smallfactorial

#include<stdio.h>
int fact(int k)
{
int j,f=1;
for(j=1;j<=k;j++)
f*=j;
return f;
}
int main()
{
int t,i,n[100],s[100],j;
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d",&n[i]);
}
for(j=0;j<t;j++)
{
s[j]=fact(n[j]);
printf("%d \n",s[j]);
}
return 0;
}
You are asked to calculate factorials of some small positive integers.
Input
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output
For each integer n given at input, display a line with the value of n!
Example
Sample input:
4
1
2
5
3
Sample output:
1
2
120
6
Your code will give correct results for the given test cases but that doesn't prove that your code works. It is wrong is because of integer overflow. Try to calculate 100! by your program and you'll see what's the problem.
My answer lacked details. I'll update this to add details for an answer to the question as it stands now.
C has limitations over the the maximum and minimum size that can be stored in a variable. For doing arbitrary precision arithmetic it is usually advisable to use a bignum library as PHIFounder has suggested.
In the present case however, the use of external libraries is not possible. In this case arrays can be used to store integers exceeding the maximum value of the integers possible. OP has already found this possibility and used it. Her implementation, however, can use many optimizations.
Initially the use of large arrays like that can be reduced. Instead of using an array of 100 variables a single variable can be used to store the test cases. The use of large array and reading in test cases can give optimization only if you are using buffers to read in from stdin otherwise it won't be any better than calling scanf for reading the test cases by adding a scanf in the for loop for going over individual test cases.
It's your choice to either use buffering to get speed improvement or making a single integer instead of an array of 100 integers. In both the cases there will be improvements over the current solution linked to, on codechef, by the OP. For buffering you can refer to this question. If you see the timing results on codechef the result of buffering might not be visible because the number of operations in the rest of the logic is high.
Now second thing about the use of array[200]. The blog tutorial on codechef uses an array of 200 elements for demonstrating the logic. It is a naive approach as the tutorial itself points out. Storing a single digit at each array location is a huge waste of memory. That approach also leads to much more operations leading to a slower solution. An integer can at least store 5 digits (-32768 to 32767) and can generally store more. You can store the intermediate results in a long long int used as your temp and use all 5 digits. That simplification itself would lead to the use of only arr[40] instead of arr[200]. The code would need some additional changes to take care of forward carry and would become a little more complex but both speed and memory improvements would be visible.
You can refer to this for seeing my solutions or you can see this specific solution. I was able to take the use down to 26 elements only and it might be possible to take it further down.
I'll suggest you to put up your code on codereview for getting your code reviewed. There are many more issues that would be best reviewed there.
Here, your array index should start with 0 not 1 , I mean j and ishould be initialized to 0 in for loop.
Besides, try to use a debugger , that will assist you in finding bugs.
And if my guess is right you use turbo C, if yes then my recommendation is that you start using MinGW or Cygwin and try to compile on CLI, anyway just a recommendation.
There may be one more problem may be which is why codechef is not accepting your code you have defined function to accept the integer and then you are passing the array , may be this code will work for you:
#include<stdio.h>
int fact(int a[],int n)// here in function prototype I have defined it to take array as argument where n is array size.
{
int j=0,f=1,k;
for (k=a[j];k>0;k--)
f*=k;
return f;
}
int main()
{
int t,i,n[100],s[100],j;
setbuf(stdout,NULL);
printf("enter the test cases\n");
scanf("%d",&t); //given t test cases
for(i=0;i<t;i++)
{
scanf("%d",&n[i]); //value of the test cases whose factorial is to be calculated
}
for(j=0;j<t;j++)
{
s[j]=fact(&n[j],t);// and here I have passed it as required
printf("\n %d",s[j]); //output
}
return 0;
}
NOTE:- After the last edit by OP this implementation has some limitations , it can't calculate factorials for larger numbers say for 100 , again the edit has taken the question on a different track and this answer is fit only for small factorials
above program works only for small numbers that means upto 7!,after that that code not gives the correct results because 8! value is 40320
In c language SIGNED INTEGER range is -32768 to +32767
but the >8 factorial values is beyond that value so integer cant store those values
so above code can not give the right results
for getting correct values we declare the s[100] as LONG INT,But it is also work
only for some range

Resources