Why isn't this program showing any number above 3? - c

Wrote this to find the prime numbers between 2 to 1000. But it stops after showing that 2 and 3 are prime numbers. I know I can find how to write a code for finding out prime numbers on the internet. But I really need to know what's going wrong here.
#include <stdio.h>
main() {
int i, j;
int ifPrime = 1;
for (i = 2; i < 1000; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
ifPrime = 0;
break;
}
}
if (ifPrime == 1) {
printf("%d is prime\n", i);
}
}
}

The line
int ifPrime=1;
must be inside the outer for loop. There it will be initialized for every i. This corresponds to the natural language words "to check whether a number i is prime, first assume it is. Then check if it is divisible". The code you had before said "to check whether the numbers 2 to 1000 are prime, first assume they are", and this wording was too broad.
The code should be:
int main()
{
for (int i = 2; i < 1000; i++)
{
int ifPrime = 1;
for (int j = 2; j < i; j++)
I replaced main with int main since that is required since 20 years. (You should not learn programming from such old books.)
I moved the int i and the int j into the for loops so that you cannot accidentally use these variables outside the scope where they have defined values.
To avoid this bug in the future, it's a good idea to extract the is_prime calculation into a separate function. Then you would have been forced to initialize the ifPrime in the correct place.
Another way of finding the cause of this bug is to step through the code using a debugger and ask yourself at every step: does it still make sense what the program is doing?

You are not setting ifPrime back to 1 after checking for the single number. So once you get a number that is non_prime, ifPrime is now 0 and hence if(ifPrime == 1) would never return true post that and hence you only see 2, 3 as prime
#include <stdio.h>
int main(void) {
for( int i=2;i<1000;i++)
{
int ifPrime = 1;
for(int j=2;j<i;j++)
{
if(i%j==0)
{
ifPrime=0;
break;
}
}
if(ifPrime==1)
{
printf("%d is prime\n",i);
}
}
return 0;
}

Related

What is wrong with my hash function?

I'm trying to create a hash table. Here is my code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define N 19
#define c1 3
#define c2 5
#define m 3000
int efort;
int h_table[N];
int h(int k, int i)
{
return (k + i*c1 + i*i*c2) % N;
}
void init()
{
for (int i = 0; i < N; i++)
h_table[i] = -1;
}
void insert(int k)
{
int position, i;
i = 0;
do
{
position = h(k, i);
printf("\n Position %d \n", position);
if (h_table[position] == -1)
{
h_table[position] = k;
printf("Inserted :elem %d at %d \n", h_table[position], position);
break;
}
else
{
i += 1;
}
} while (i != N);
}
void print(int n)
{
printf("\nTable content: \n");
for (int i = 0; i < n; i++)
{
printf("%d ", h_table[i]);
}
}
void test()
{
int a[100];
int b[100];
init();
memset(b, -1, 100);
srand(time(NULL));
for (int i = 0; i < N; i++)
{
a[i] = rand() % (3000 + 1 - 2000) + 2000;
}
for (int i = 0; i < N ; i++)
{
insert(a[i]);
}
print(N);
}
int main()
{
test();
return 0;
}
Hash ("h") function and "insert" function are took from "Introduction to algorithms" book (Cormen).I don't know what is happening with the h function or insert function. Sometimes it fills completely my array, but sometimes it doesn't. That means it doesn't work good. What am I doing wrong?
In short, you are producing repeating values for position often enough to prevent h_table[] from being populated after only N attempts...
The pseudo-random number generator is not guaranteed to produce a set of unique numbers, nor is your h(...) function guaranteed to produce a mutually exclusive set of position values. It is likely that you are generating the same position enough times that you run out of loops before all 19 positions have been generated. The question how many times must h(...) be called on average before you are likely to get the value of an unused position? should be answered. This may help to direct you to the problem.
As an experiment, I increased the looping indexes from N to 100 in all but the h(...) function (so as not to overrun h_table[] ). And as expected the first 5 positions filled immediately. The next one filled after 3 more tries. The next one 10 tries later, and so on, until by the end of 100 tries, there were still some unwritten positions.
On the next run, all table positions were filled.
2 possible solutions:
1) Modify hash to improve probability of unique values.
2) Increase iterations to populate h_table
A good_hash_function() % N may repeat itself in N re-hashes. A good hash looks nearly random in its output even though it is deterministic. So in N tries it might not loop through all the array elements.
After failing to find a free array element after a number of tries, say N/3 tries, recommend a different approach. Just look for the next free element.

Creating a program in C to generate primes

I am trying to generate a list of all the prime numbers for the first 1000 numbers.
I am not sure where I am going wrong in my code. From what I can tell, my nested for loop is not reading dividing/reading the array correctly and then assigning that array the proper value. How can I fix it?
The program currently only generates all the odd numbers.
int main() {
int x = 1;
int arr[500];
int i, j, k;
int counter;
int primearray[500];
for (j = 0; j <= 500; j++) {
x += 2;
arr[j] = x;
for (k = 1; k <= 15; k++) {
counter = x % k;
if (counter == 0) {
primearray[j] = x;
} else {
break;
}
}
for (i = 0; i < 500; i++) {
printf("%d ", primearray[i]);
}
}
Please invest time in learning how to indent your code. Choose a style that suits you and use it consistently: this will make your programs easier to read, and in turn easier to understand.
As I'm writing this, your posted code doesn't even compile because a closing curly brace } is missing: such editing mistakes are made possible by misleading indentation. Also note that in a properly written C program you must remember to #include any standard headers that are used:
#include <stdio.h> // for `printf()`
Rather than try to fix your algorithm, which at first glance doesn't make any sense to me anyway, I will try to help you restructure your program.
Keep main() simple
Given that the goal of your program is checking which of the first 1000 natural numbers are prime, the main() function should do no more than loop through those numbers and print the ones which are prime, like this:
for (int n=0; n < 1000; ++n)
if (is_prime(n))
printf("%d\n", n);
Putting them in an array instead of printing is equally easy:
int prime_array[500]; // array of primes
int k=0; // current index in array of primes
for (int n=0; n < 1000; ++n)
if (is_prime(n))
prime_array[k++] = n;
Break up the program in several functions
In accordance to the previous idea, write short and simple functions that do one thing, and do it well. In your case, you should write the is_prime() function to determine if a number is prime or not. You can start from here:
///
/// #brief Checks if a number is prime.
/// #param [in] n Number to be checked
/// #returns Whether `n` is prime or not.
/// #retval 1 If `n` is prime.
/// #retval 0 If `n` is not prime.
///
int is_prime(int n)
{
// TODO: add code here
}
Decide how to check for primality
There is a Primality test article on Wikipedia that you should read.
First, you must correctly handle these special cases:
0 is not prime
1 is not prime
2 is prime
// TODO: also check 1 and 2 in a similar fashion
if (n == 0)
return 0;
After this is done, you can use a naive and inefficient algorithm that checks the other numbers:
// try divisors from 2 to n-1
for (int d=2; d < n; ++d)
if (n % d == 0) // if the division was even,
return 0; // the number is not prime
return 1; // if we get here, the number is prime
If you want to use a faster (but more complicated) algorithm for checking primes, look back at the Wikipedia article linked above. Notice how you'd only have to change the code inside is_prime() and the rest of the program would work the same, unchanged.
As I understood from your code, arr is an array of possible candidates and primearray is an array of approved ones. No every candidate will be approved one so you need different variables for indexing them.
The second issue is the algorithm for approving candidates. From this part of your code (I changed some indents)
for (k = 1; k <= 15; k++) {
counter = x%k;
if (counter == 0) {
primearray[j] = x;
} else {
break;
}
follows that you approve a candidate if it is divisible by all integers from 1 to 15 - I am sorry but prime numbers have not this property.
I think you could refer to this code which will generate all prime numbers up to the number that you specify. I think this will be more optimised.
void main()
{
int n, i, j, temp=0;
printf("Enter a number \n");
scanf("%d", &n);
printf(" Prime numbers -\n");
for(i=2; i<n+1; i++)
{
temp = 0;
for(j=2; j<i; j++)
{
if(i%j == 0)
{
temp = 1;
break;
}
}
if(temp == 0)
{
printf("%d \n", i);
}
}
getch();
}

printing randome choices from an array

I am working on a function that picks random numbers from a given array and prints them to stdout. These numbers should not repeat and how many numbers are picked is given to the function along with the array. I have a separate test file for the function and a header file as well. Everything compiles fine but when I run the program I get a hang up in the pickNumbers function, nothing is printed and I don't even know if anything is being chosen to begin with.
#include <stdio.h>
#include <stdlib.h>
#include "head.h"
//program that picks random numbers from the given array
int alreadyPicked(int choices[], int choice);
void pickNumbers(int myArray[],int max)
{
// delcare/initilize variables
int i;
int choices[max];
int length = sizeof(myArray)/sizeof(myArray[0]);
// seed rand
srand(time(NULL));
// pick a random choice until that given number of choices is reached
// to make sure non repeat run against alreadyPicked function
for (i=0; i <= max; i++) {
do{
choices[i] = (rand() % max);
}while (alreadyPicked(choices, choices[i]) == TRUE);
}
for (i=0; i <= max; i++) {
printf("%d", myArray[choices[i]]);
}
printf("\n");
}
int alreadyPicked(int choices[], int choice)
{
int i;
int answer = FALSE;
for (i=0; i <= (sizeof(choices)/sizeof(choices[0])); i++) {
if(choices[i] == choice)
answer = TRUE;
}
return answer;
}
Perhaps
for (i=0; i <= max; i++) {
must be:
for (i=0; i < max; i++) {
and
for (i=0; i <= (sizeof(choices)/sizeof(choices[0])); i++) {
must be:
for (i=0; i < (sizeof(choices)/sizeof(choices[0])); i++) {
In your first "for" loop you have a nested while/do. You increment "i" in your for loop, instead you should increment the variable inside of while/do, otherwise it will hang forever performing such loop because "i" is never incremented.
Replace:
for (i=0; i <= max; i++) {
by:
for (i=0; i < max;) {
And also replace:
choices[i] = (rand() % max);
By:
choices[i++] = (rand() % max);
This way you make sure "i" is being incremented. Also your construction "i<=max" is incorrect since you start from 0, use the way David RF did.
Apart from the aforementioned wrong loop tests, the reason for the endless loop is that in alreadyPicked() you compare the new choice index with every choice index in choices[], including uninitialized ones and the new one itself; thus, alreadyPicked() always returns TRUE. I suggest to change to call of alreadyPicked() to
alreadyPicked(choices, i)
and its implementation to
int alreadyPicked(int choices[], int choice)
{
for (int i = 0; i < choice; i++)
if (choices[i] == choices[choice])
return TRUE;
return FALSE;
}

C programming - A array and a random number combined question?

this is the part of my code I'm having trouble with. I can't understand why its doing it wrong. I have an array where it stores numbers 0 - 25 which are cases. The numbers are to be randomized and overwritten into the array. Only condition is is that no number can be doulbes, there can only be one of that number. I'm not asking you to do my code but do hint me or point me in the write directions. I am trying to learn :)
The problem lies within the second do loop. I can get the numbers to be randomized, but I get doubles. I have created a loop to check and fix this, but it's not working. The code does run, and doubles do still happen and I can't see why. It looks correct to me. Please look, thank you (:
This is what I have done originally (at the very end is where I am at now):
int check_double = 0;
int i = 0;
int counter = 0;
int array_adder = 0;
int random_number = 0;
int cases[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26
};
float money[] = {
0.01,1,5,10,25,50,75,100,200,300,400,500,750,1000,5000,10000,25000,50000,750000,100000,200000,300000,400000,500000,750000,1000000
};
//Randomize all case number and realine them in the array
srand ( time(NULL) );
do
{
cases[counter]= rand() % 26;
counter += 1;
printf("%d\n", cases[counter]);
}
while (counter <= 25);
//make sure there are no doubles in the array, just 0 - 25 and not a single number repeated twice
do
{
check_double = 0;
for (i = 0; i < counter; i++)
{
if (cases[counter] == cases[i])
{
cases[counter] = rand()% 26;
check_double == 1;
}
}
}
while (check_double != 0);
Currently, what I had achived after that was combing both loops and check for doubles as the array goes. This is what I made, it still has doubles and im not sure why, I only posted the cose with both loops combined:
do
{
cases[counter]= rand() % 26;
if (cases[counter]>=1);
for(i=0;i<=counter;i++)
if (cases[counter]==cases[i])
{
cases[counter]=rand()% 26;
}
printf("%d\n",cases[counter]);
counter+=1;
}
Robsta, you could try the following piece of code, I have run this in Dev-C++, any changes that you require can be made from your side. But, I assure you that this code generates what you intend.
int check_double = 0;
int i = 0;
int counter = 0;
int cases[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26
};
//Randomize all case number and realine them in the array
srand ( time(NULL) );
do
{
cases[counter]= rand() % 26;
for(i=0;i<counter;i++)
if (cases[counter]==cases[i]){
while (cases[counter]==cases[i])
{
cases[counter]=rand()% 26;
}
i=0;
}
printf("%d\t%d\n",counter,cases[counter]);
counter+=1;
}while (counter <= 25);
If you have any clarifications required, I would love to discuss with you.
-Sandip
You're only ever writing over the last value in the array:
for(i=0;i<counter;i++)
if (cases[counter]==cases[i])
You need to loop through as you are, then have an inner loop, where you compare all the other entries to the current one.
Even easier would be to do the loop where you set each random number, so when you set cases[3] for example, loop from 0 to 2 and check to see if your new value for 3 clashes, if so, wash - rinse - repeat!
You have this line of code:
check_double==1;
That doesn't change check_double because it's ==, not =. == compares; it doesn't assign. Change that line to this:
check_double=1;
A helpful compiler (clang in this example) will give you a warning about this:
test.c:5:14: warning: expression result unused [-Wunused-value]
check_double==1;
~~~~~~~~~~~~^ ~
You can't check for duplicates with a single loop. You need to at least compare every possible pair of elements to be able to see if there's a duplicate. I'm guessing you forgot to loop over counter somewhere inside the second do...while?
Note that your method is not guaranteed to terminate. (Very, very likely but not certain.) Why don't you simply shuffle the cases array? Shuffling is simple but tricky; see Fisher-Yates (or Knuth) Shuffle for a simple algorithm.
If you are asking how to randomly sequence the number 1-25 then you could do something like this. This is a very brute-force way of generating the sequence, but it does work and might give you a starting point for something more optimized.
#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#include <conio.h>
const int LastNumber = 25;
bool HasEmpty(int available[LastNumber][2])
{
bool result = false;
for(int i = 0; i < LastNumber; i++)
{
if (available[i][1] == 0)
{
result = true;
break;
}
}
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
int available[LastNumber][2];
int newSequence[LastNumber];
srand((unsigned int)time(NULL));
for(int i = 0; i < LastNumber; i++)
{
available[i][0]=i;
available[i][1]=0;
}
int usedIndex = 0;
while (HasEmpty(available))
{
int temp = rand() % (LastNumber + 1);
if (available[temp][1] == 0)
{
newSequence[usedIndex++] = available[temp][0];
available[temp][1] = 1;
}
}
for(int i = 0; i < LastNumber; i++)
{
printf("%d\n",newSequence[i]);
}
getch();
return 0;
}

Finding the largest palindrome of the product of two three digit numbers problem

So on Project Euler the Problem 4 states the following:
A palindromic number reads the same
both ways. The largest palindrome made
from the product of two 2-digit
numbers is 9009 = 91 99.
Find the largest palindrome made from
the product of two 3-digit numbers.
I have tried the following:
#include <stdio.h>
#include <stdlib.h>
int check(int result)
{
char b[7];
sprintf(b, "%d", result);
if (b[0] == b[5] && b[1] == b[4] && b[2] == b[3])
{
return 1;
}
else
{
return 0;
}
}
int main () {
int i;
int g;
int final;
for (i = 999; i > 99; i--)
{
for (g = 999; g > 99; g--)
{
if (check(g*i) == 1)
{
final = g*i;
goto here;
}
}
}
here:
printf("%d", final);
}
But, this does not work. Instead of the right answer, I get 580085, which I guess is a palindrome at least, but still not the right answer.
Let me explain my program starting from int main:
int i and int g are my multipliers. They are those two three digit numbers.
int final is the number that will store the largest palindrome.
I start two for loops going to down to get every number possibility.
I get out of the loop using a goto when the first palindrome is reached(probably should not but, it doesn't effect a small program like this too much).
The first palindrome should be the biggest one possible since I am counting down from the top.
Let me now explain my check:
First off since these are two three digit numbers multiplying together to determine the size a char would need to be to hold that value I went to a calculator and multiplied 999 * 999 and it ended up being 6 then I need to add one because I found out from one the questions I posted earlier that sprintf puts a \0 character at the end.
Ok, now that I have a char and all, I copied result (which i*g in int main) and put it in char b[7].
Then I just checked b to see if it equalled it self with by hard coding each slot I needed to check for.
Then I returned accordingly, 1 for true, and 2 for false.
This seems perfectly logical to me but, it does not work for some weird reason. Any hints?
This assumption is wrong:
The first palindrome should be the biggest one possible since I am counting down from the top.
You will check 999*100 = 99900 before 998*101 = 100798, so clearly you canĀ“t count on that.
The problem is that the first palindrome that you find is not the bigger one for sure.
Just an example:
i = 900, g = 850 -> 765000
i = 880, g = 960 -> 844800
The first one is smaller, but since you iterate first on i, then on g it will be discovered first.
Ok, they are not palindrome but the concept is the same..
I think you are tackling this problem back to front. It would be more efficient to generate the palindromes from highest to lowest then check by factorizing them. First one that has two three digit factors is the answer.
e.g.
bool found = false;
for (int i = 998; i >= 100; i--)
{
char j[7];
sprintf(j,"%d",i);
j[3]= j[2];
j[4]= j[1];
j[5]= j[0];
int x =atoi(j);
int limit = sqrt((float) x);
for (int z = 999; z >= limit; z--)
{
if (x%z==0){
printf("%d",x);
found = true;
break;
}
}
if (found) break;
}
The first palindrome should be the biggest one possible since I am counting down from the top
The problem is that you might have found a palindrome for a large i and a small g. It's possible that there's a larger palindrome that's the product of j and k where:
i > j and
g < k
(I hope this makes sense).
Java Implementation:
public class Palindrome {
public static void main(String[] args)
{ int i, j;
int m = 1;
int k =11;
boolean flag = false;
while (true)
{;
if (flag) j = m + 1;
else j = m;
for (i = k; i > 0; i--)
{
j++;
int number, temp, remainder, sum = 0;
number = temp = (1000 - i) * (1000 - j);
while (number > 0)
{
remainder = number % 10;
number /= 10;
sum = sum * 10 + remainder;
}
if (sum == temp)
{
System.out.println("Max value:"+temp);
return;
}
}
if (flag)
m++;
k=k+11;
flag = !flag;
}
}
}
A word on performance. You have the possibility of duplicating many of the products because you are using a pretty simple nested loop approach. For instance, you start with 999*999 and then 999*998, etc. When the inner loop finishes, you will decrement the outer loop and start again with 998*999, which is the same as 999*998.
Really, what you want to do is start the inner loop with the same value as the current outer loop value. This will eliminate your duplicate operations. Something like this...
for (i = 999; i > 99; i--)
{
for (g = i; g > 99; g--)
{
...
However, as Emilio pointed out, your assumption that the first palindrome you find will be the answer is incorrect. You need to compute the biggest numbers first, obviously. So you should try them in this order; 999*999, 999*998, 998*998, 999*997, 998*997, etc...
Haven't tested it but I think you want something like this (pseudo code):
x = 999;
n = 0;
while (++n <= x)
{
j = x;
k = j - n;
while (j >= k)
{
y = j-- * k;
if (check(y))
stop looking
}
}
I found this article which might help you. It has improved brute force approach.
All the above provided answers are excellent, but still I could not restrict myself from writing the code. The code posted by #thyrgle is absolutely perfect. Only a slight correction which he needs to do is just check which product is the maximum.
The code can be as
int i,j,max=0,temp;
for(i=999;i>=100;i--){
for(j=i;j>=100;j--){
temp=i*j;
if(isPalin(temp) && temp>max){
max=temp;
}
}
}
cout<<max<<"\n";
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int a[6];
void convertToString(int xy){
int i,t=100000;
for(i=0;i<6;i++){
a[i]=xy/t;
xy = xy % t;
t=t/10;
}
}
int check(){
int i;
for(i=0;i<3;i++){
if(a[i]!=a[6-i]){
return 0;
}
}
return 1;
}
void main(){
int x,y,xy,status=0;
int i=0,j=0,p=0;
for(x=999;x>99;x--){
for(y=x;y>99;y--){
xy=x*y;
convertToString(xy);
status = check();
if(status==1){
if(xy>p){
p=xy;
i=x;
j=y;
}
}
}
}
printf("\nTwo numbers are %d & %d and their product is %d",i,j,p);
}
x,y=999,999
k=0
pal=[]
while (y>99):
while (x>=100):
m=x*y
n=x*y
while (n!=0):
k=k*10+(n%10)
n=int(n/10)
if(m==k):
if k not in pal:
pal.append(k)
x=x-1
k=0
else:
y,x=y-1,999
pal.sort()
print(pal)
it gives 906609 as the largest palindrome number

Resources