dividing two array elements - c

main()
{
int prime_array[2339],prime1_count=0,mul1_count=0;
int i, prime, lim_up, lim_low, n,j=0;
int mul,count=0;
int mul_count[65026]={0},number[7096];
printf("\n ENTER THE LOWER LIMIT…: ");
scanf("%d", &lim_low);
printf("\n ENTER THE UPPER LIMIT…: ");
scanf("%d", &lim_up);
for(n=lim_low+1; n<lim_up; n++)
{
prime = 1;
for(i=2; i<n; i++)
if(n%i == 0)
{
prime = 0;
break;
}
if(prime)
{
prime_array[j]=n;
j++;
}
}
for(i=1;i<=255;i++)
{
for(j=1;j<=255;j++)
{
mul = j*i;
mul_count[mul]++;
}
}
for(i=1;i<=65025;i++)
if( mul_count[i]!=2 && mul_count[i]!=0 )
{
number[count]=i;
count++;
}
for(prime1_count=0;prime1_count<2339;prime1_count++)
{
printf("\nprime number used is:%d",prime_array[prime1_count]);
for(mul1_count=0;mul1_count<7096;mul1_count++)
{
printf("\n%d\t",number[mul1_count] % prime_array[prime1_count]);
}
}
}
I want to find the modulus of (number[mul1_count] % prime_array[prime1_count] ), but the output which I get is wrong. What is the mistake here. The prime number should be in the range 40000 to 65025. What changes should i make here?

I don't really know what you are trying to do but when running your program I am getting a Floating Point Exception and thats because of the number[mul1_count] % prime_array[prime1_count] when prime_array[prime1_count] is 0
Wrap your inner for loop with an if(prime_array[prime1_count] != 0)
for(prime1_count=0;prime1_count<2339;prime1_count++)
{
if(prime_array[prime1_count] != 0)
{
printf("\nprime number used is:%d",prime_array[prime1_count]);
for(mul1_count=0;mul1_count<7096;mul1_count++)
{
printf("\n%d\t",number[mul1_count] % prime_array[prime1_count]);
}
}
}
It would be good to also try to explain what you want to do, what you expect, what you get, etc...
Edit :
Also, as a sidenote. You should slightly change the loop which calculates the prime numbers. The reason is that you do not keep track of how many prime numbers you calculated. and then you
for(prime1_count=0;prime1_count<2339;prime1_count++)
iterate through the whole prime_array[].
Imagine the situation where you only calculated 5 prime numbers, this means that the remaining array is left with whatever. No reason to do the extra calculation, leaving asside that the prime_array is not initialized to zero nowhere in the code which means it (afaik) contains garbage value, in the indeces where no prime number was allocated with your algorithm. This means that the
if(prime_array[prime1_count] != 0)
will probably fail if you think that garbage value exist there.
Either initialize the prime_array[2339] = { 0 };
OR
I would do that :
int number_of_primes=0;
for(n=lim_low+1; n<lim_up; n++)
{
prime = 1;
for(i=2; i<n; i++)
if(n%i == 0)
{
prime = 0;
break;
}
if(prime)
{
if(number_of_primes < 2338)
{
prime_array[number_of_primes]=n;
number_of_primes++;
}else
{
break;
}
}
}
....
for(prime1_count=0 ; prime1_count < number_of_primes+1 ; prime1_count++)
{
printf("\nprime number used is:%d",prime_array[prime1_count]);
for(mul1_count=0;mul1_count<7096;mul1_count++)
{
printf("\n%d\t",number[mul1_count] % prime_array[prime1_count]);
}
}

Related

its works perfectly except when i enter the integer '2'

#include <stdio.h>
#include <stdlib.h>
//this function checks if the given number prime or not
int prime_check(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return 1;
} else if (number == 2) {
return 0;
} else {
return 0;
}
}
}
//the problem is that when i entered the integer 2 i got that "the number is not prime" output
int main() {
int user_n;
printf("pls enter the number \n");
scanf("%d", & user_n);
if (prime_check(user_n) == 0) {
printf("the number is prime \n");
} else {
printf("its not prime.. \n");
}
}
If the selected number is 2, the for loop is never entered because i < number is initially false. The function then reaches the end without returning a value.
If a function is declared to return a value but does not, and the calling function attempts to use the return value, this triggers undefined behavior in your program, which basically means that no particular result is guaranteed.
Related to this, you have a logic error. The body of the for loop has a return statement in every path so no more that one iteration of the loop will occur. This causes all odd numbers to be reported as prime.
You only need to perform the % check inside of the loop. If that condition is not met, then continue on with the loop. If the loop exits, then you know you have a prime number and can return 0.
int prime_check(int number)
{
for (int i = 2;i<number;i++){
if (number % i == 0){
return 1;
}
}
return 0;
}
Also, you can reduce the number of loop iterations by changing the condition to i<=number/i (which is mathematically the same as i*i<=number but avoids overflow), since you don't need to check values greater than the square root of the number in question.
You can't enter to for loop only if the condition i < number is TRUE
SO you should check if number = 2 and number < 2 before your for loop
The new version of your code:
#include <stdio.h>
#include <stdlib.h>
int prime_check(int number) {
if (number == 2) {
return 0;
} else if (number < 2) {
return 1;
} else {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return 1;
} else if (number == 2) {
return 0;
} else {
return 0;
}
}
}
}
int main() {
int user_n;
printf("pls enter the number \n");
scanf("%d", & user_n);
if (prime_check(user_n) == 0) {
printf("the number is prime \n");
} else {
printf("its not prime.. \n");
}
}

How to make an array accept only numbers in c programming?

So my task is to make an array that accepts 10 characters. If the characters entered by the user are greater than 10, then an error is dispayed. If the 10 characters entered contain a letter, it displays another error.
Therefore, the array can only have 10 numbers and nothing else, if the numbers entered are less or more than 10, error is displayed as well as if there are letters in the array.
My code accepts both numbers and letters, as i cannot figure out how to display error when letters are entered.
void getTenDigitPhone(char telNum[])
{
int i;
int z = 1;
do
{
scanf("%s", telNum);
if (strlen(telNum) != 10)
{
printf("Enter a 10-digit phone number: ");
z = 1;
}
else if (strlen(telNum) == 10)
{
return telNum;
}
} while (z == 1);
}
You just need to check that telNum contains only digits:
for (int i = 0; i < 10; i++)
if (!isdigit(telNum[i])) {
// handle error because a non-digit was found.
}
I'm not going to do your homework for you but this should give you the idea.
You can use the function isdigit(x).
This returns true (non-zero) if x is a digit and returns false (zero) if not.
You have to check digit by digit.
I'm going to give an answer because you have posted your current code as your effort. As other answers you should use isdigit(x) function.
...
else if (strlen(telNum) == 10)
{
int i;
char err = 0;
for (i = 0; i < 10; i++) {
if (!isdigit(telNum[i])) {
// Your error here
printf("Non-digit character found");
err = 1;
break;
}
}
if (err == 0) {
return telNum;
}
}
...

Seven thieves & diamonds riddle C program

I recently wrote a C program for the following 'Seven thieves and diamonds' puzzle:
"There are seven thieves, They steal diamonds from a diamond merchant and run away in jungle. While running, night sets in and they decide to rest in the jungle When everybody’s sleeping, two of the best friends get up and decide to distribute the diamonds among themselves and run away. So they start distributing but find that one diamond was extra. So they decide to wake up 3rd one and divide the diamonds again …..only to their surprise they still find one diamond extra. So they decide to wake up fourth one. Again one diamond is spare. 5th woken up……still one extra. 6th still one extra. Now they wake up 7th and diamonds are distributed equally."
Although the logic is quite simple to understand, my program seems to be quite buggy. It only seems to run for the numbers 3, 5 and 7.
I am new to programming in general and I feel that my program is not very sophisticated:
#include<stdio.h>
int main()
{
int n,i,j,k;
int a[30];
printf("Enter the number of thieves\n");
scanf("%d",&n);
i=n+1;
while(1)
{
j=2;
k=0;
while(j<n)
{
if(i%j == 1 && i%n==0)
{
a[k]=1;
}
else
{
a[k]=0;
}
if(k==n-2)
{
k=0;
}
j++;
k++;
}
for(j=0;j<n-1;j++)
{
if(a[j]==0)
{
break;
}
else if(j==n-3 && a[j] == 1)
{
printf("The number of diamonds = %d\n",i);
return;
}
}
i++;
}
}
It would be great if someone could help me develop this code into something more nonspecific, such that it could return an output for all values of 'n.' Also, any feedback in general would be highly appreciated.
Your code is very hard to follow, so I wrote my own code to debug this and your program although obscure and hard to follow is completely correct for valid inputs, you are just not handling all the cases very well thus you are in a while loop forever. Not every input will work for this problem only prime numbers will give you an answer for this problem so inputs like 2, 4, and 6 will not work so they need to be handled.
Here is a test comparing your outputs with the test I wrote for valid inputs.
#Of Theives Your Code Test Code
3 3 3
5 25 25
7 301 301
11 25201 25201
13 83161 83161
You can write a quick function to test for this care of this like this:
int isPrime(int tmp)
{
int i;
for(i = 2; i <= tmp/2; i++)
{
if(tmp % i == 0)
return 0;
}
return 1;
}
Then you can check for valid inputs which numbers greater than 1 (because then there would not be enough thiefs for the story to happen) and prime like so:
#include<stdio.h>
int isPrime(int tmp)
{
int i;
for(i = 2; i <= tmp/2; i++)
{
if(tmp % i == 0)
return 0;
}
return 1;
}
int main()
{
int n,i,j,k;
int a[30];
printf("Enter the number of thieves that is prime and greater than 1\n");
scanf("%d",&n);
i=n+1;
if(isPrime(n) && n > 1)
{
while(1)
{
j=2;
k=0;
while(j<n)
{
if(i%j == 1 && i%n==0)
{
a[k]=1;
}
else
{
a[k]=0;
}
if(k==n-2)
{
k=0;
}
j++;
k++;
}
for(j=0;j<n-1;j++)
{
if(a[j]==0)
{
break;
}
else if(j==n-3 && a[j] == 1)
{
printf("The number of diamonds = %d\n",i);
return;
}
}
i++;
}
}
else
{
printf("Input Invalid.\n");
}
}
The code I wrote to test the riddle:
#include<stdio.h>
int isPrime(int tmp)
{
int i;
for(i = 2; i <= tmp/2; i++)
{
if(tmp % i == 0)
return 0;
}
return 1;
}
long gcd(long a, long b) {
if (b == 0) {
return a;
}
else {
return gcd(b, a % b);
}
}
int main()
{
int thieves, i;
long diamonds, lcm = 1;
printf("Enter the number of thieves that is prime and greater than 1:\n");
scanf("%d",&thieves);
if(isPrime(thieves) && thieves > 1)
{
for(i = 2;i < thieves;i++)
{
lcm = (lcm*i)/gcd(i,lcm);
}
i = 1;
dimonds = lcm*i + 1;
while(dimonds % thieves != 0)
{
dimonds = lcm*++i + 1;
}
printf("There are a minimum of diamonds is: %d\n",diamonds);
}
else
{
printf("Input inv\n");
}
}

How to show the digits which were repeated in c?

The question is that show the digits which were repeated in C.
So I wrote this:
#include<stdio.h>
#include<stdbool.h>
int main(void){
bool number[10] = { false };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] == true)
{
printf("%d ", digit);
}
number[digit] = true;
n /= 10;
}
return 0;
}
But it will show the repeated digits again and again
(ex. input: 55544 output: 455)
I revised it:
#include<stdio.h>
int main(void){
int number[10] = { 0 };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] == 1)
{
printf("%d ", digit);
number[digit] = 2;
}
else if (number[digit] == 2)
break;
else number[digit] = 1;
n /= 10;
}
return 0;
}
It works!
However, I want to know how to do if I need to use boolean (true false), or some more efficient way?
To make your first version work, you'll need to keep track of two things:
Have you already seen this digit? (To detect duplicates)
Have you already printed it out? (To only output duplicates once)
So something like:
bool seen[10] = { false };
bool output[10] = { false };
// [...]
digit = ...;
if (seen[digit]) {
if (output[digit])) {
// duplicate, but we already printed it
} else {
// need to print it and set output to true
}
} else {
// set seen to true
}
(Once you've got that working, you can simplify the ifs. Only one is needed if you combine the two tests.)
Your second version is nearly there, but too complex. All you need to do is:
Add one to the counter for that digit every time you see it
Print the number only if the counter is exactly two.
digit = ...;
counter[digit]++;
if (counter[digit] == 2) {
// this is the second time we see this digit
// so print it out
}
n = ...;
Side benefit is that you get the count for each digit at the end.
Your second version code is not correct. You should yourself figured it out where are you wrong. You can try the below code to print the repeated elements.
#include<stdio.h>
int main(void){
int number[10] = { 0 };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] > 0)
{
number[digit]++;;
}
else if (number[digit] ==0 )
number[digit] = 1;
n /= 10;
}
int i=0;
for(;i<10; i++){
if(number[i]>0)
printf("%d ", i);
}
return 0;
}
In case you want to print the repeated element using bool array (first version) then it will print the elements number of times elements occur-1 times and in reverse order because you are detaching the digits from the end of number , as you are seeing in your first version code output. In case you want to print only once then you have to use int array as in above code.
It is probably much easier to handle all the input as strings:
#include <stdio.h>
#include <string.h>
int main (void) {
char str[256] = { 0 }; /* string to read */
char rep[256] = { 0 }; /* string to hold repeated digits */
int ri = 0; /* repeated digit index */
char *p = str; /* pointer to use with str */
printf ("\nEnter a number: ");
scanf ("%[^\n]s", str);
while (*p) /* for every character in string */
{
if (*(p + 1) && strchr (p + 1, *p)) /* test if remaining chars match */
if (!strchr(rep, *p)) /* test if already marked as dup */
rep[ri++] = *p; /* if not add it to string */
p++; /* increment pointer to next char */
}
printf ("\n Repeated digit(s): %s\n\n", rep);
return 0;
}
Note: you can also add a further test to limit to digits only with if (*p >= '0' && *p <= '9')
output:
$./bin/dupdigits
Enter a number: 1112223334566
Repeated digit(s): 1236
Error is here
if (number[digit] == true)
should be
if (number[digit] == false)
Eclipse + CDT plugin + stepping debug - help you next time
As everyone has given the solution: You can achieve this using the counting sort see here. Time complexity of solution will be O(n) and space complexity will be O(n+k) where k is the range in number.
However you can achieve the same by taking the XOR operation of each element with other and in case you got a XOR b as zero then its means the repeated number. But, the time complexity will be: O(n^2).
#include <stdio.h>
#define SIZE 10
main()
{
int num[SIZE] = {2,1,5,4,7,1,4,2,8,0};
int i=0, j=0;
for (i=0; i< SIZE; i++ ){
for (j=i+1; j< SIZE; j++){
if((num[i]^num[j]) == 0){
printf("Repeated element: %d\n", num[i]);
break;
}
}
}
}

How can I compute if a value is prime or not faster?

My programs runs well in my compiler but it shows time limit exceeds in online contest compiler.
First line of input will contain a number N = number of test cases. Next N lines will contain number n as test case where 0<=n<=1000000000
Here is my code.
#include<stdio.h>
void main()
{
long t,n,i;
int f = 0;
scanf("%lu",&t);
while(t--)
{
scanf("%lu",&n);
f=0;
if(n==0 || n==1)
{
printf("NOT PRIME\n");
}
else
{
for(i=2;i<=n/2;i++)
{
if(n%i == 0)
{
printf("NOT PRIME\n");
f =1;
break;
}
}
if(f==0)
{
printf("PRIME\n");
}
}
}
}
How can I execute this program faster. Help me. Thanks in advance.
You can iterate to square root of n instead of n/2. Also you can pre-calculate all the prime factors in the range of square root of 1000000000 before the while loop. Then try to divide n with the prime factors that are less than or equal to sqrt(n) to check if it is prime or not.
The for loop:
(i = 3; i <= sqrt(n); i += 2) // skip 2 because it's the only even prime
Also you only need to test odd numbers for primality (two being the only even prime).
And compile with optimization, e.g. -O3 if using gcc.
You can make with increment 2:
My function to verify if a number is prime:
bool check(int n)
{
int i, j;
bool isprime;
if(n%2 == 0 || n == 0 || n == 1)
{
isprime = false;
}
else if(n == 2 || n == 3)
{
isprime = true;
}
else
{
for(i = 3; i<n; i+=2)
{
if(n%i == 0)
{
isprime = false;
break;
}
else if(i == n-2)
{
isprime = true;
break;
}
}
}
return isprime;
}
Remembering that call a function is less fast than use directly in main function.
Without changing your algorithm:
for(i=2;i<=n/2;i++)
might be faster as:
for(i=2, m=n/2; i<=m; ++i)
you only calculate the end value once, and preincrement doesn' compute an intermediate value like the post increment does.
However, with decent compiler optimizations, both of these will already be done.
Without looking at the generate assembly, it is hard to do any aggressive optimization.

Resources