Smallest odd number in given array - c

This code is supposed to find the smallest odd number in given array and store it in min but when I try to print min it always prints 0.
int smallestodd(int x[5]){
int j;
int k[5];
int p = 0;
int r = 0;
for(int h =0; h<5;h++){
j = x[h] % 2;
if(j == 1){
int temp =x[h];
k[p] =temp;
p++;
}
}
int min = k[0];
while(k[r] !=0){
if(k[r] < min ){
min = k[r];
r++;
}
}
return min;
}

Assuming there is an odd number in the array -- let's say trying to find the minimum odd number in an array with just even numbers (or no numbers) is UB :)
index = 0;
while (arr[index] % 2 == 0) index++; // skip even numbers
min = arr[index++]; // first odd number
while (index < length) {
if (arr[index] % 2) {
if (arr[index] < min) min = arr[index];
}
index++;
}

this code avoid overflow in search and return 1 when found or 0 if array has only even numbers.
int getMinOdd(int arr[], int length, int *value) {
int found = 0;
for(int idx=0; idx < length; idx++) {
if (arr[idx] % 2) {
if (!found || *value > arr[idx]) {
*value = arr[idx];
}
found = 1;
}
}
return found;
}

It's quite simple actually. You need to just check 2 conditions on your array.
int smallestOdd(int arr[]){
int min = 99999; //Some very large number
for(int i = 0; i < (length of your array); i++) {
if(arr[i]%2 != 0 && arr[i] < min) { //Check if number is odd and less than the current minimum value
min = arr[i];
}
}
return min;
}

Use this using statement as first :
Using System Linq;
Console.WriteLine(myArray.Where(i => i%2 == 1).Min());

Related

Finding the second largest element in array without sorting

I know about the single traversal method initialising two variables to INT_MIN. But my question is why do we initialise two variables to INT_MIN and also what is the purpose of INT_MIN here?
Why can't we initialise two variables to its first element like I have done in the code below? Because when I hand-checked the code manually, I found nothing wrong. So why doesn't the code run properly?
#include <stdio.h>
int main(void) {
int x[10];
int i, n;
int first = x[0];
int second = x[0];
printf("Input the size of array :");
scanf("%d", &n);
printf("Input %d elements in the array :\n", n);
for (i = 0; i < n; i++) {
printf("x[%d]: ", i);
scanf("%d", &x[i]);
}
for (i = 0; i < n; ++i) {
if (first < x[i]) {
second = first;
first = x[i];
} else
if (x[i] > second && x[i] != first) {
second = x[i];
}
}
if (second == first)
printf("There is no second largest element\n");
else
printf("\nThe Second largest element in the array is: %d", second);
return 0;
}
There are several problems in your code:
the array x is defined with a length of 10, but uninitialized when you set first and second to the value of its first element.
you do not test the return value of scanf(), leading to undefined behavior in case of input failure.
you do not test of n is in less or equal to 10 before reading values into x.
you need to special case n <= 0 as no values will be read into x.
Here is a modified version:
#include <stdio.h>
int main(void) {
int x[10];
int i, n, first, second;
printf("Input the size of array :");
if (scanf("%d", &n) != 1 || n < 0 || n > 10) {
printf("invalid input\n");
return 1;
}
if (n <= 0) {
first = second = 0;
} else {
printf("Input %d elements in the array:\n", n);
for (i = 0; i < n; i++) {
printf("x[%d]: ", i);
if (scanf("%d", &x[i]) != 1) {
printf("invalid input\n");
return 1;
}
}
first = second = x[0];
for (i = 1; i < n; ++i) {
if (first < x[i]) {
second = first;
first = x[i];
} else
if (x[i] > second && x[i] != first) {
second = x[i];
}
}
}
if (second == first)
printf("There is no second largest element\n");
else
printf("\nThe Second largest element in the array is: %d\n", second);
return 0;
}
Regarding an alternative implementation where first and second are initialized to INT_MIN and the loop starts at i = 0, the trick is INT_MIN is the smallest possible int value, so first will compare <= to all values of the array and therefore will not shadow a smaller value. It is also a good default return value for a function that finds the maximum value in an array when passed an empty array.
For your case study, the INT_MIN approach is does not work and the algorithm would fail on an array with a single repeated value: at the end of the scan, first would be set to that value and second would still be INT_MIN.
testing first == second would yield a second largest value equal to INT_MIN, which is incorrect.
testing second == INT_MIN to determine if all values are identical would be incorrect too as an array with values { 1, INT_MIN } would indeed have a second largest value equal to INT_MIN.
Your approach works correctly and the alternative would need to be written differently, with an extra variable. Indeed the solution presented in this article is incorrect, and so is this one, this one, this one and countless more random code across the Internet.
I've added some comments where I saw some problems. Hopefully I caught all the problems. Code below.
#include <stdio.h>
int main(void) {
// int x[10]; I moved this to under where you ask the user for the array size.
int i, n;
// int first=x[0]; This should be written after the user has inputted their numbers. Because what is in x[0]? user hasn't entered anything yet
// int second=x[0]; Same reason as ^
printf("Input the size of array :");
scanf("%d",&n);
int x[n]; // This should be here because you asked the user what the size of the array is.
printf("Input %d elements in the array :\n",n);
for(i=0; i<n; i++)
{
printf("x[%d]: ", i);
scanf("%d", &x[i]);
}
// You should put your first and second int's here
int first=x[0];
int second=x[0];
for (i=0; i<n ; ++i)
{
if (first<x[i])
{
second = first;
first = x[i];
}
else if (x[i] > second && x[i] != first)
{
second = x[i];
}
}
if (second == first)
printf("There is no second largest element\n");
else
printf("\nThe Second largest element in the array is: %d", second);
return 0;
}
int first=x[0];
int second=x[0];
x isn't initialized yet.
Prints -1 if no second largest element is found.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int findNotSame(long long int a[],long int n)
{
long long int temp = a[0];
int flag = 0;
long int i;
for(i=0;i<n;i++)
{
if(a[i]!=temp)
return 1;
}
return 0;
}
long long int findMax(long long int a[],long int n)
{
long int i;
long long int max = a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
max = a[i];
}
return max;
}
int main() {
long int i,j,n;
scanf("%ld",&n);
long long int a[n];
if(n<2) //There cannot be scond largest if there;s only one(or less) element.
{
printf("-1");
return 0;
}
for(i=0;i<n;i++) //Read elements.
scanf("%lld",&a[i]);
if (!findNotSame(a,n)) //Check if all the elements in array are same if so, then -1.
{
printf("-1");
return 0;
}
long long int max = findMax(a,n); //Find maximum element(first).
long long int max2 = -999999999999999; //Initialize another max which will be the second maximum.
for(i=0;i<n;i++) //Find the second max. element.
{
if(a[i]>max2 && a[i] != max)
max2 = a[i];
}
if(max == max2) //Incase if second max(largest) is same as maximum
max2 = -1;
printf("%lld",max2);
return 0;
}
All solution is better, but some fail when the same items available in the array
like,
int arr[] = {56, 41, 19, 33, 13, 23, 25, 56};
56 available in two times,
so for this solution,
int arr[] = {56, 41, 19, 33, 13, 23, 25,56};
var max = arr[0];
var secMax=-1;
var size = arr.length;
for(var l = 1; l < size; l++) {
if (max < arr[l]) {
secMax = max;
max = arr[l];
} else if (secMax < arr[l] && arr[l] != max) {
secMax = arr[l];
}
}
System.out.println("Second largest number :-" + secMax);
import ast
input_str = input()
input_list = ast.literal_eval(input_str)
if len(input_list)<2:
print("not present")
else:
i=input_list[0]
j=i
for index_val in input_list[1:]:
if i<index_val:
j=i
i=index_val
elif index_val>j and index_val!=i:
j=index_val
elif i==j and index_val<j:j=index_val
if i==j:
print("not present")
else:
print(j)
This works,
val arr=Array(4,1,2,4,5,5,7,18,10,5,7)
var firstAndSecondIndex:(Int,Int)=null
for(indexVal <- 2 to (arr.size -1))
firstAndSecondIndex match {
case null =>
println("0,0")
firstAndSecondIndex=(0,1)
case value =>
value match {
case value if arr(indexVal) == arr(value._1) || arr(indexVal) == arr(value._2) =>
println("equals")
case value if arr(indexVal) > arr(value._1) =>
println("1,0")
value match {
case value if arr(indexVal) > arr(value._2) && arr(value._1) > arr(value._2) =>
firstAndSecondIndex=(indexVal,value._1)
case value if arr(indexVal) > arr(value._2) && arr(value._1) < arr(value._2) =>
firstAndSecondIndex=(indexVal,value._2)
case value if arr(indexVal) < arr(value._2) =>
firstAndSecondIndex=(indexVal,value._2)
}
case value if arr(indexVal) < arr(value._1) =>
println("1,1")
value match {
case value if arr(indexVal) > arr(value._2) =>
firstAndSecondIndex=(indexVal,value._1)
case value if arr(indexVal) < arr(value._2) =>
println("not greater")
}
}
}
val secondLargest= arr(firstAndSecondIndex._1) < arr(firstAndSecondIndex._2) match {case true => arr(firstAndSecondIndex._1) case false => arr(firstAndSecondIndex._2)}
int arr[] = {56, 41, 19, 33, 13, 23, 25};
int max = 1;
int secondMax = 0;
for (int i = 0; i < arr.length; i++) {
int getValue = arr[i];
if (max == 1) {
max = getValue;
secondMax = arr[1];
} else {
if (max < getValue) {
secondMax = max;
max = getValue;
} else if (secondMax < getValue) {
secondMax = getValue;
} else {
// Nothing Do
}
}
}
System.out.println("" + secondMax);
Java code to find the largest and second largest number in an array without sorting and using a single loop:
package programs;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int largest = -1;
int secondlargest = -1;
int numberPos = -1;
int numberPos1 = -1;
int[] arr = {22, 33, 9000, 70, 9000, -1, -10, -3, 22, 99, 100, 10000};
for (int i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
numberPos = i;
largest = arr[i];
}
}
for (int i = 0; i < arr.length; i++) {
if (secondlargest < arr[i] && secondlargest < largest && arr[i] != largest) {
secondlargest = arr[i];
numberPos1 = i;
}
}
System.out.println("Largest number is "+largest+" with position "+numberPos);
System.out.println("Second largest is "+secondlargest+" with position "+numberPos1);
}
}

C program returning 0 instead of max occurring integer from sequence of integer input

I posted earlier about a runtime error in my C program but now I'm having another issue with the code. My program runs fine without any errors but it always prints 0 no matter what the input. I've spent the last 4 hours trying to figure out why my code is doing that but I've had no luck. I would really appreciate if someone could give me a hand.
My program takes in an input of a sequence of integers, using another program that works like scanf. Getint() reads an input of a sequence of integers and stops reading the input when it reaches EOF (-1). The number of integers in the sequence is 1000.
// ar_max(a[]) returns the max entry of a
int ar_max(int a[]) {
int max_so_far = a[0];
for (int i = 1; i < 1000; i++) {
if (a[i] > max_so_far) {
max_so_far = a[i];
}
}
return max_so_far;
}
int main() {
int inputnum = getint();
// array containing the distinct numbers seen
int a_num[1000] = {};
// array containing the frequencies of the distinct numbers seen
int a_freq[1000] = {};
int len_n = 0;
while (inputnum != EOF) {
int i = 0;
len_n = i + 1;
int len_f = len_n;
// update the frequency of inputnum if it's already been seen
for (i = 0; i < len_f; i++, len_n += 1) {
if (a_num[i] == inputnum) {
a_freq[i] = a_freq[i] + 1;
}
}
// add inputnum into the array if it hasn't already been seen
if (i == len_n) {
a_num[i+1] = inputnum;
a_freq[i+1] = 1;
}
inputnum = getint();
}
// print the first number with the highest frequency
for (int j = 0; j < len_n; j++) {
if (a_freq[j] == ar_max(a_freq)) {
printf("%d\n", a_num[j]);
break;
}
}
}
For example, an input of
10 20 30 20
should result in 20
The code has the right idea, but it still has some problems.
First, you have two arrays with related information. You keep two lengths for each of these arrays and try to keep the lengths the same. That's complicated. Instead, consider having just one length for both arrays.
When you loop thorugh the array in oder to check whether the given number is already contained in the array:
for (i = 0; i < len_f; i++, len_n += 1) {
if (a_num[i] == inputnum) {
a_freq[i] = a_freq[i] + 1;
}
}
you update then length of the number array with each iteration. You shouldn't, because you are not changing the length of anything while iterating though the loop.
Next, you check whether the number hasn't been found with:
if (i == len_n) ...
That doesn't work, because you update the frequency in the first loop, but don't terminate the loop; your condition will always be true. You can fix this by breaking out of the loop explicitly with break when you have found the number. (Better yet, make the look-up and frequency update a function whose return value indicates whether the element was found and add the elemen if it wasn't.)
When you append the new element:
if (i == len_n) {
a_num[i+1] = inputnum;
a_freq[i+1] = 1;
}
you should, of course, increment the length of the array you append to. In general, appending an item to an array looks like this:
array[len++] = item;
Recall that the first index is zero and that the actual length is one beyond the valid indices.
There are other points:
When you add an element, you should make sure that you don't overflow the array. The dimension of 1000 is generous, but not infinite.
In your function ar_max, you iterate over all 1000 elements of the array. You have initialised the arrays to zero, so the maximum will still be right, but it is better to pass the array size to the function, too, so that you can iterate over only the actual items.
If your function ar_max returned an index instead of a value, you could access both array with that index and you wouldn't need the last loop over j, because j is just that index.
If you have two parallel arrays, it is a good idea to create a struct that hold the item and frequency and always keeps them together. That simplifies the code, because you don't have to keep anything in sync. Such a data layout also lends itself to sorting and filtering other common operations.
Here's a version that implements the fixes described above. It also uses a function to look up an element by value and makes ar_max return an array index instead of a value.
#include <stdlib.h>
#include <stdio.h>
#define MAX 1000
int getint()
{
int x;
if (scanf("%d", &x) < 1) return EOF;
return x;
}
int ar_max(const int a[], int len)
{
if (len == 0) return -1;
int max_so_far = a[0];
int max_index = 0;
for (int i = 1; i < len; i++) {
if (a[i] > max_so_far) {
max_so_far = a[i];
max_index = i;
}
}
return max_index;
}
int ar_find(const int a[], int len, int which)
{
for (int i = 0; i < len; i++) {
if (a[i] == which) return i;
}
return -1;
}
int main()
{
int inputnum = getint();
int a_num[MAX] = { }; // distinct numbers seen
int a_freq[MAX] = { }; // frequencies of the distinct numbers
int len = 0; // actual length of both arrays
while (inputnum != EOF) {
int i = ar_find(a_num, len, inputnum);
if (i < 0) { // append new item
if (len >= MAX) {
fprintf(stderr, "Array size %d exceeded\n", MAX);
exit(1);
}
a_num[len] = inputnum;
a_freq[len] = 1;
len++;
} else { // increment existing item
a_freq[i]++;
}
inputnum = getint();
}
int imax = ar_max(a_freq, len);
if (imax >= 0) {
printf("%d (%d times)\n", a_num[imax], a_freq[imax]);
} else {
puts("Empty input.");
}
return 0;
}
int main()
{
// array containing the distinct numbers seen
int a_num[1000] = {0};
// array containing the frequencies of the distinct numbers seen
int a_freq[1000] = {0};
int len_n = 0;
int i = 0, j = 0;
// Read first entry
int inputnum = getint();
if (EOF == inputnum)
{
printf("No valid number input given\n");
return -1;
}
// Make first entry in a_num and a_freq
a_num[0] = inputnum;
a_freq[0] = 1;
// Update len_n to 1
len_n = 1;
// Get new entry from user and update number array and frequency array
inputnum = getint();
while (inputnum != EOF)
{
// update the frequency of inputnum if it's already been seen
for (i = 0; i < len_n; i++)
{
if (a_num[i] == inputnum)
{
a_freq[i] = a_freq[i] + 1;
break;
}
}
// add inputnum into the array if it hasn't already been seen
if (i == len_n)
{
a_num[i] = inputnum;
a_freq[i] = 1;
// Update len_n
len_n++;
}
// Check if we have already reached 1000
if (1000 == len_n)
{
printf("Reached 1000 entry read\n");
break;
}
// Next entry
inputnum = getint();
}
// print the number with the highest frequency
int max_freq = ar_max(a_freq);
for (j = 0; j < len_n; j++)
{
if (a_freq[j] == max_freq)
{
printf("%d\n", a_num[j]);
break;
}
}
}
NOTE:
1. #define MAX_SIZE 1000 can be used since hardcoded value 1000 is used repeatedly in code. This will help when you have use new size (say 1500) and you need to change only the #define MAX_SIZE 1500, other code remains unchanged.
2. ar_max() function can be modified to give array index where max occurs to avoid the for loop in main to find the array index. e.g.
int ar_max(int a[])
{
int index = 0;
int max_so_far = a[0];
for (int i = 1; i < 1000; i++) {
if (a[i] > max_so_far) {
max_so_far = a[i];
index = i;
}
}
return index;
}
In main():
printf("%d\n", a_num[ar_max(a_freq)]);

Return which digit occurs the most times

I have to return which digit in a number occurs the most frequently ( though not how many times it occurs )
So far I can only get this, I don't know how to isolate the digit, only to show how many times each digit occurs.
#include <stdio.h>
int frequentDigit(int);
int main()
{
frequentDigit(123032333);
return 0;
}
int frequentDigit(int arg)
{
int tmp; int i; int myArr[9] = { 0 };
tmp = (arg < 0) ? -arg : arg;
do
{
myArr[tmp % 10]++;
tmp /= 10;
} while (tmp != 0);
for (i = 0; i < 9; i++) { printf("\nThere are %d occurances of digit %d", myArr[i], i); }
}
The array where you are storing the frequency of the digits, i.e myArr[]. Its suppose to hold the frequency of all the number from 0...9. And since there are 10 numbers, you would need an array of lenght 10.
int myArr[10];
Later, you need to traverse through the array once, checking for the max element, and saving the index accordingly, to find which number has occured most number of times.
To traverse, the for loop should go till 9
for (i = 0; i <= 9; i++)
Edited
As someone commented, you can find the max value while you are computing the frequencies itself.
int max = -1, max_num = -1;
do
{
myArr[tmp % 10]++;
if( myArr[tmp % 10] > max)
{
max = myArr[tmp % 10];
max_num = tmp % 10;
}
tmp /= 10;
} while (tmp != 0);
printf("%d", max_num);
Its simple. At the end of your code you have an array of frequencies, if you find the max of that you get the most common element
Just use a loop to find the max and print that:
int max = myArr[0]; // start with max = first element
int max_position=0;
for(int i = 1; i<9; i++)
{
if(myArr[i] > max){
max = myArr[i];
max_position=i;
}
}
printf("\The max is %d occuring %d times ", max_position, max_position)

recursive function C ranking

#include <stdio.h>
#include <stdlib.h>
int cnt = 0; Count // global variable declaration
int find_max(int n, int arr[]); // (Recursive) function declaration circulation
int main() {
// Insert code here ...
int number; // Generate sequence number
int * score; // Declare the game
int i; // Loop variable
int max; // Function return value
scanf("% d \ n", &number); // Input (number of sequence)
score = (int *)malloc(sizeof(int) * number); // Allocate memory scores
for (i = 0; i < number; i++) {
scanf("% d", &score[i]);
} // Scores input
max = find_max(number, score); // Recursive function call.
printf("% d% d \ n", max, cnt); // Count value and second value, etc.
return 0;
}
int find_max(int n, int arr[]) {
int maxnum1 = 0; // Maximum value of the partial sequence 1
int maxnum2 = 0; // Maximum value of the partial sequence 2
int max = 0; // Maximum value
int secondMax = 0; // 2 deunggap
int * s1, *s2, sn1, sn2; // Memory allocation variables
int i, j; // Loop variable
cnt++; // If the sequence number is not zero and the count + 1.
if (n == 1) {
return arr[0]; // The number of returns a value of 1 when the sequence.
}
else if (n % 2 == 0) {// if even
s1 = (int *)malloc(sizeof(int) * n / 2); // Split assignment
for (i = 0; i < n / 2; i++) {
s1[i] = arr[i];
} // Where assigned sequences into storage
sn1 = n / 2;
s2 = (int *)malloc(sizeof(int) * n / 2); // Split assignment
for (j = 0; j < n / 2; j++)
{
s2[j] = arr[i];
i++;
} // Where assigned sequences into storage
sn2 = n / 2;
}
else {
s1 = (int *)malloc(sizeof(int) * (n + 1) / 2); // Split assignment
for (i = 0; i < ((n + 1) / 2); i++) {
s1[i] = arr[i];
} // Where assigned sequences into storage
sn1 = ((n + 1) / 2);
i = ((n + 1) / 2);
s2 = (int *)malloc(sizeof(int) * (n - 1) / 2); // Split assignment
for (j = 0; j < ((n - 1) / 2); j++)
{
s2[j] = arr[i];
i++;
} // Where assigned sequences into storage
sn2 = ((n - 1) / 2);
}
maxnum1 = find_max(sn1, s1); // Partial recursive sequence maximum value twirl
maxnum2 = find_max(sn2, s2); // Partial recursive sequence maximum value twirl
for (i = 0; i < n; i++) {
// If the value of the current index is greater than the maximum value
if (arr[i] > = max) {
// Sets the maximum value previously stored before the update of the maximum value.
secondMax = max;
// Maximum updates
max = arr[i];
}
else if ((arr[i] > secondMax && arr[i] < max) || max == secondMax) {// if the value is greater than ten thousand and one memories of the calculated value max
secondMax = arr[i];
}
}
if (secondMax == 0) {
return max;
}
else {
return secondMax; // 2 deunggap return
}
}
I'll use recursive function in c, ranking for second. not first.
but, input and output are
4
9 0 0 0
9(score) 7(recursive function count)
However , output is 9. I don't want to this result.
Not first, second is 0
Correct result is 0 7.
How do i for correct result 0 7.
help me please.
This is an extraordinarily complicated way of finding the second highest integer in an array, but I think the problem is here. The second highest value is 0, but you discard it in favour of the highest value. If you had initialised max and secondMax to -1 (and test for -1) that would solve it.
if (secondMax == 0) {
return max;
}
else {
return secondMax;
}
Here is a simpler way:
#include<stdio.h>
#include<limits.h>
int main(void)
{
int i, max1 = INT_MIN, max2 = INT_MIN;
int score[] = { 9, 0, 0, 0 };
int number = sizeof(score) / sizeof(score[0]);
for (i=0; i<number; i++) {
if (max1 < score[i])
max1 = score[i];
if (max2 < score[i] && max1 > score[i])
max2 = score[i];
}
if (max2 == INT_MIN)
max2 = max1;
printf ("max1 = %d, max2 = %d\n", max1, max2);
return 0;
}
Program output:
max1 = 9, max2 = 0
The problem is that secondMax and max are initialized with a number you can find in the array.
You can avoid this problem by using the first number in the array to initialize max and secondMax, and then start the loop with the second number of the array. The last loop of you function could be:
max = arr[0];
secondMax = max;
for (i = 1; i < n; i++) {
// If the value of the current index is greater than the maximum value
if (arr[i] > = max) {
// Sets the maximum value previously stored before the update of the maximum value.
secondMax = max;
// Maximum updates
max = arr[i];
}
else if ((arr[i] > secondMax && arr[i] < max) || max == secondMax) {// if the value is greater than ten thousand and one memories of the calculated value max
secondMax = arr[i];
}
}
if (secondMax == max) {
return max;
}
else {
return secondMax; // 2 deunggap return
}

Project Euler Problem 4

I've created a solution to problem 4 on Project Euler.
However, what I find is that placing the print statement (that prints the answer) in different locations prints different answers. And for some reason, the highest value of result is 580085. Shouldn't it be 906609? Is there something wrong with my isPalindrome() method?
#include <stdio.h>
#include <stdbool.h>
int isPalindrome(int n);
//Find the largest palindrome made from the product of two 3-digit numbers.
int main(void)
{
int i = 0;
int j = 0;
int result = 0;
int palindrome = 0;
int max = 0;
//Each iteration of i will be multiplied from j:10-99
for(i = 100; i <= 999; i++)
{
for(j = 100; j <= 999; j++)
{
result = i * j;
if(isPalindrome(result) == 0)
{
//printf("Largest Palindrome: %d\n", max); //906609
//printf("Result: %d\n", result); //580085
if(result > max)
{
max = result;
//printf("Largest Palindrome: %d\n", max); //927340
}
printf("Largest Palindrome: %d\n", max); //906609
}
}
}
//printf("Largest Palindrome: %d\n", max); //998001
system("PAUSE");
return 0;
} //End of main
//Determines if number is a palindrome
int isPalindrome(int num)
{
int n = num;
int i = 0;
int j = 0;
int k = 0;
int count = 0;
int yes = 0;
//Determines the size of numArray
while(n/10 != 0)
{
n%10;
count++;
n = n/10;
}
int numArray[count];
//Fill numArray with each digit of num
for(i = 0; i <= count; i++)
{
numArray[i] = num%10;
//printf("%d\n", numArray[i]);
num = num/10;
}
//Determines if num is a Palindrome
while(numArray[k] == numArray[count])
{
k = k + 1;
count = count - 1;
yes++;
}
if(yes >= 3)
{
return 0;
}
}//End of Function
I remember doing that problem a while ago and I simply made a is_palindrome() function and brute-forced it. I started testing from 999*999 downwards.
My approach to detect a palindrome was rather different from yours. I would convert the given number to a string and compare the first char with the nth char, second with n-1 and so on.
It was quite simple (and might be inefficient too) but the answer would come up "instantly".
There is no problem in the code in finding the number.
According to your code fragment:
.
.
}
printf("Largest Palindrome: %d\n", max); //906609
}
}
}
//printf("Largest Palindrome: %d\n", max); //998001
system("PAUSE");
.
.
.
you get the result as soon as a palindrome number is found multiplying the number downwards.
You should store the palindrome in a variable max and let the code run further as there is a possibility of finding a greater palindrome further.
Note that for i=800,j=500, then i*j will be greater when compare with i=999,j=100.
Just understand the logic here.
A few issues in the isPalindrome function :
the first while loop doesn't count the number of digits in the number, but counts one less.
as a result, the numArray array is too small (assuming that your compiler supports creating the array like that to begin with)
the for loop is writing a value past the end of the array, at best overwriting some other (possibly important) memory location.
the second while loop has no properly defined end condition - it can happily compare values past the bounds of the array.
due to that, the value in yes is potentially incorrect, and so the result of the function is too.
you return nothing if the function does not detect a palindrome.
//Determines if number is a palindrome
bool isPalindrome(int num) // Change this to bool
{
int n = num;
int i = 0;
int j = 0;
int k = 0;
int count = 1; // Start counting at 1, to account for 1 digit numbers
int yes = 0;
//Determines the size of numArray
while(n/10 != 0)
{
// n%10; <-- What was that all about!
count++;
n = n/10;
}
int numArray[count];
//Fill numArray with each digit of num
for(i = 0; i < count; i++) // This will crash if you use index=count; Array indices go from 0 to Size-1
{
numArray[i] = num%10;
//printf("%d\n", numArray[i]);
num = num/10;
}
//Determines if num is a Palindrome
/*
while(numArray[k] == numArray[count-1]) // Again count-1 not count; This is really bad though what if you have 111111 or some number longer than 6. It might also go out of bounds
{
k = k + 1;
count = count - 1;
yes++;
}
*/
for(k = 1; k <= count; k++)
{
if(numArray[k-1] != numArray[count-k])
return false;
}
return true;
}//End of Function
That's all I could find.
You also need to change this
if(isPalindrome(result) == 0)
To
if(isPalindrome(result))
The Code's Output after making the modifications: Link
The correct printf is the one after the for,after you iterate through all possible values
You are using int to store the value of the palidrome but your result is bigger then 65536,
you should use unsigned
result = i * j;
this pice of code is wrong :
while(n/10 != 0) {
n%10;
count++;
n = n/10;
}
it should be:
while(n != 0) {
count++;
n = n/10;
}
As well as the changes that P.R sugested.
You could do something like this to find out if the number is palindrome:
int isPalindrom(unsigned nr) {
int i, len;
char str[10];
//convert number to string
sprintf(str, "%d", nr);
len = strlen(str);
//compare first half of the digits with the second half
// stop if you find two digits which are not equal
for(i = 0; i < len / 2 && str[i] == str[len - i - 1]; i++);
return i == len / 2;
}
I converted the number to String so I'd be able to go over the number as a char array:
private static boolean isPalindrom(long num) {
String numAsStr = String.valueOf(num);
char[] charArray = numAsStr.toCharArray();
int length = charArray.length;
for (int i = 0 ; i < length/2 ; ++i) {
if (charArray[i] != charArray[length - 1 - i]) return false;
}
return true;
}
I got correct answer for the problem, but I want to know is my coding style is good or bad from my solution. I need to know how can I improve my coding,if it is bad and more generic way.
#include<stdio.h>
#define MAX 999
#define START 100
int main()
{
int i,j,current,n,prev = 0;
for(i = START;i<=MAX;i++)
{
for(j=START;j<=MAX;j++)
{
current = j * i;
if(current > prev) /*check the current value so that if it is less need not go further*/
{
n = palindrome(current);
if (n == 1)
{
printf("The palindrome number is : %d\n",current);
prev = current; // previous value is updated if this the best possible value.
}
}
}
}
}
int palindrome(int num)
{
int a[6],temp;
temp = num;
/*We need a array to store each element*/
a[5] = temp % 10;
a[4] = (temp/10) %10;
a[3] = (temp/100) %10;
a[2] = (temp/1000) %10;
a[1] = (temp/10000) %10;
if(temp/100000 == 0)
{
a[0] = 0;
if(a[1] == a[5] && a[2] == a[4])
return 1;
}
else
{
a[0] = (temp/100000) %10;
if(a[0] == a[5] && a[1] == a[4] && a[2] == a[3])
return 1;
else
return 0;
}
}
No, the largest should be: 906609.
Here is my program:
def reverse_function(x):
return x[::-1]
def palindrome():
largest_num = max(i * x
for i in range(100, 1000)
for x in range(100, 1000)
if str(i * x) == reverse_function(str(i * x)))
return str(largest_num)
print(palindrome())

Resources