As new to competitive programming, I was solving this practice question. The goal is to write a program to display numbers whose digits are 1 greater than the corresponding digits of the entered number. So if the number input is 12345 then the output number should be 23456. I have figured out how to separate each number and add them, but I was unable able to take a number of test cases in the following program.
The question is as follows
Input
First line of input will contain a number N = number of test cases. Next N lines will contain number n as test case where 1<=n<=99999.
Output
For each input case, add one to each digit of n, and print the new number.
As a beginner in competitive programming would be helpful if you give some tips to optimize the code.
here is the code that I have written.
#include<stdio.h>
void main()
{
int n, t, sum = 0;
scanf("%d", &t);
int a[t];
for (int j = 0; j < t; j++)
{
for (int i = 0; i < t; i++)
{
scanf("%d", &n);
a[i] = n;
if (t == 1) {
if (i == 0) {
a[i] = (a[i] + 1) * 1;
}
}
else if (t == 2) {
if (i == 0) {
a[i] = (a[i] + 1) * 10;
}
else if (i == 1) {
a[i] = (a[i] + 1) * 1;
}
}
else if (t == 3) {
if (i == 0) {
a[i] = (a[i] + 1) * 100;
}
else if (i == 1) {
a[i] = (a[i] + 1) * 10;
}
else if (i == 2) {
a[i] = (a[i] + 1) * 1;
}
}
else if (t == 4) {
if (i == 0) {
a[i] = (a[i] + 1) * 1000;
}
else if (i == 1) {
a[i] = (a[i] + 1) * 100;
}
else if (i == 2) {
a[i] = (a[i] + 1) * 10;
}
else if (i == 3) {
a[i] = (a[i] + 1) * 1;
}
}
else if (t == 5) {
if (i == 0) {
a[i] = (a[i] + 1) * 10000;
}
else if (i == 1) {
a[i] = (a[i] + 1) * 1000;
}
else if (i == 2) {
a[i] = (a[i] + 1) * 100;
}
else if (i == 3) {
a[i] = (a[i] + 1) * 10;
}
else if (i == 4) {
a[i] = (a[i] + 1) * 1;
}
}
else if (t == 6) {
if (i == 0) {
a[i] = (a[i] + 1) * 100000;
}
else if (i == 1) {
a[i] = (a[i] + 1) * 10000;
}
else if (i == 2) {
a[i] = (a[i] + 1) * 1000;
}
else if (i == 3) {
a[i] = (a[i] + 1) * 100;
}
else if (i == 4) {
a[i] = (a[i] + 1) * 10;
}
else if (i == 4) {
a[i] = (a[i] + 1) * 1;
}
}
}
}
for (int i = 0; i < t; i++)
{
sum = sum + a[i];
}
printf("%d\n", sum);
}
I've reworked on the code from beginning and I've made a solution for you:
#include <stdio.h>
int main(void)
{
int num, sum, remainder, check; // check used as a boolean expression
sum = check = 0;
printf("Enter the sequence: ");
scanf("%d", &num);
while (num > 0)
{
remainder = num % 10; // each time num is reduced
if (remainder != 9)
{
if (check == 0)
sum = (10 * sum) + (remainder + 1);
else
{
sum = (10 * sum) + (remainder + 2);
check = 0;
}
}
else
{
sum = (10 * sum) + 0;
check = 1;
}
num /= 10; // will divide and execute in each iteration until it's true
}
num = sum; // final number will be equal to the sum
sum = 0;
// Summing up the results
while (num > 0)
{
remainder = num % 10;
sum = (10 * sum) + remainder;
num /= 10;
}
printf("Result: %d\n", sum);
return 0;
}
Test Output
Enter the sequence: 23456
Result: 34567
It's just all about the sum & remainder. Hope it helps you understand better.
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int num,i=1,j;
Scanner scan=new Scanner(System.in);
int numo=scan.nextInt();num=numo;
for(;numo>0;numo=numo/10,i=i*10)
{
num=num+i;
if(numo%10==9)
num=num-i*10;
}
System.out.println(num);
}
}
The below solution uses the basic remainder and reverse approach:
int addOne(int n)
{
int rem, ans=0, p=1 ;
while(n>0)
{
rem = n%10;
(rem == 9)?rem = 0:rem+=1;
ans+=p*rem;
p*=10;n/=10;
}
return ans;
}
int main() {
int n;
cin>>n;
cout<<addOne(n);
return 0;
}
Related
i have a code and im trying to get a O(sqrt(n)) without using math library in c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int is_abundant(int num);
int main()
{
int num;
scanf("%d", &num);
printf("%d\n", is_abundant(num));
return 0;
}
int is_abundant(int num)
{
int sum = 1;
for (int i = 1; i < num; i++) {
if (num % i == 0)
{
sum += i;
}
}
sum = sum - num;
if (sum > num)
{
return 1;
}
else
return 0;
}
what can i do to get O(sqrt(n)) ? any help ?
When num % i == 0 is true, num % (num / i) == 0 will also be true.
Therefore, you can reduce the loop
for (int i = 1; i < num; i++) {
if (num % i == 0)
{
sum += i;
}
}
to
if (num > 1) {
for (int i = 1; i * i <= num; i++) {
if (num % i == 0)
{
sum += i;
if (num / i > i) sum += num / i;
}
}
}
Note that simply changing the condition i < num to i * i <= num will allow it to enter the loop when num = 1, so I added an if statement to deal with this case.
For finding out factors you don't have to run the loop till n times, rather you can just run it till i <= sqrt(n) times or if you don't want to use sqrt lib then simply multiply i two times check if it is less than or equal to num or not.
int is_abundant(int num)
{
int sum = 1;
for (int i = 1; i*i <= num; i++) {
if (num % i == 0)
{
sum += i;
sum += num/i; // if all factors you want to add, otherwise ignore
}
}
sum = sum - num;
if (sum > num)
{
return 1;
}
else
return 0;
}
I really tried but still don't know what's wrong with my code.
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
int minus, i, judge;
for (minus = 0, judge = 1; judge == 1; minus++, n -= minus) {
for (i = 2; i * i < n; i++) {
if (n % i == 0)
judge = 1;
else judge = 0;
}
if (judge == 1)
continue;
else break;
}
printf("%d\n", n);
return 0;
}
When I input 143, the output is 143 not 139.
However, when I input 11, the output is the correct answer 11.
The loop test is incorrect: for (i = 2; i * i < n; i++)
If n is the square of a prime number, the loop will stop just before finding the factor.
You should either use i * i <= n or i <= n / i.
Furthermore, you do not enumerate all numbers as you decrement n by an increasing value at each iteration.
Note also that the loop would not find the closest prime to n, but the greatest prime smaller than n, which is not exactly the same thing.
Here is a modified version:
#include <limits.h>
#include <stdio.h>
int isPrime(int n) {
if (n <= 2 || n % 2 == 0)
return n == 2;
for (int i = 3; i <= n / i; i += 2) {
if (n % i == 0)
return 0;
}
return 1;
}
int main() {
int n;
if (scanf("%d", &n) != 1)
return 1;
if (n <= 2) {
printf("2\n");
} else {
for (i = 0;; i++) {
if (isPrime(n - i))
printf("%d\n", n - i);
break;
}
if (n <= INT_MAX - i && isPrime(n + i))
printf("%d\n", n + i);
break;
}
}
}
return 0;
}
We are asked to write some code that takes a 4 digit number as input, and does the following:
Take any four-digit number, using at least two different digits.
Arrange the digits in descending and then in ascending order to get two four-digit numbers
Subtract the smaller number from the bigger number.
Go back to step 2 and repeat.
The end result will always freeze at kaprekar's constant 1674 and we must print the algorithm's resulting number each and every time . In the end we also have to print the number of times we had to run the algorithm to get there .
I worked it out as loop , storing the digits in 2 arrays and sorting the first in ascending order and the second in descending order over and over again till i get to 1674 but for some reason the "process" loop won't stop . Any help would be appreciated .
#include <stdio.h>
#include <stdlib.h>
int main()
{
long int pow1(int x, int n)
{
int i, result = 1;
for (i = 0; i < n; i++)
{ // Power Function //
result *= x;
}
return (result);
}
int a, s;
int val[] = {
0,
0,
0,
0};
int value[] = {
0,
0,
0,
0};
int ex = 0;
scanf(" %d", &a);
if (a / 1000 != 0 && a / 1000 < 10)
{
// Extracting the digits and storing them in the arrays .
for (int i = 0; i <= 3; ++i)
{
value[i] = val[i] = (a % pow1(10, i + 1) - a % pow1(10, i)) / pow1(10, i);
if (i > 0)
{
if (val[i] == val[i - 1])
{
ex++;
}
}
}
if (ex == 3)
{
printf("Wrong input");
exit(0);
}
int j = 0, k = a;
// Start of process
while (k != 6174)
{
while (1)
{
s = 0;
for (int i = 0; i <= 3; i++)
{
if (val[i] > val[i + 1])
{
int temp = val[i];
val[i] = val[i + 1];
val[i + 1] = temp;
s = 1;
}
}
if (s == 0)
{
break;
}
}
while (1)
{
s = 0;
for (int i = 0; i <= 3; i++)
{
if (value[i] < value[i + 1])
{
int temp = value[i];
value[i] = value[i + 1];
value[i + 1] = temp;
s = 1;
}
}
if (s == 0)
{
break;
}
}
j++;
printf("max:%d min: %d ", value[0] * 1000 + value[1] * 100 + value[2] * 10 + value[3], val[0] * 1000 + val[1] * 100 + val[2] * 10 + val[3]);
k = value[0] * 1000 + value[1] * 100 + value[2] * 10 + value[3] - (val[0] * 1000 + val[1] * 100 + val[2] * 10 + val[3]);
printf("diff:%d\n", k);
for (int i = 0; i <= 3; ++i)
{
value[i] = val[i] = (k % pow1(10, i + 1) - k % pow1(10, i)) / pow1(10, i);
}
}
printf("Took %d turns", j);
}
else
{
printf("Wrong input");
}
return 0;
}
You have defined val and value as 4 element [0..3], yet in your loops you access and modify both over [0..4] eg: val[i+1] = temp.
I proper sized them (int val[5] = {0}, value[5] = {0}), and your test yielded:
max:2211 min: 112 diff:2099
max:9920 min: 229 diff:9691
max:9961 min: 1699 diff:8262
max:8622 min: 2268 diff:6354
max:6543 min: 3456 diff:3087
max:8730 min: 378 diff:8352
max:8532 min: 2358 diff:6174
Took 7 turns
Because your sort isn't quite right.
If you change your sort to be:
for (int i = 1; i < 4; i++)
{
if (val[i-1] > val[i])
{
int temp = val[i];
val[i] = val[i - 1];
val[i - 1] = temp;
s = 1;
}
}
it will respect its boundaries, and be correct; so you can go back to len 4 vectors. Remember to change the other one as well.
ps: It is more work for me to complain that you didn't put a main wrapper in your example than to put one in. That doesn't excuse not doing the least you can do.
I wrote code to implement brute force in C but doesn't run.
I've tried to debug it but I got a debugger infinity loop, I need help!
int bruteForce(s_cellBoard board[9][9], int i, int arr_32[]) {
if (i == 81 || i < 0)
return 1;
//if he put number in cell
if (isPossible(board, i, arr_32))
{//check cell that is not givan- can change
do { i++; } while (board[i / 9][i % 9].isGiven);
}
else
{
board[i / 9][i % 9].value = 0;
//check cell tht is not givan- can change
do { i--; } while (board[i / 9][i % 9].isGiven);
}
return bruteForce(board, i, arr_32);
}
this function if can put number in cell
int isPossible(s_cellBoard board[9][9], int i, int arr_32[])
{
int num = board[i / 9][i % 9].value ? board[i / 9][i % 9].value+1 : 1;
for (; num <= 9 && (!row(board, i, num) || !col(board, i, num) || !block(board, i, num));num++);
if (num<= 9)
{
board[i / 9][i % 9].value = num;
printf("%d\n", board[i / 9][i % 9].value);
return 1;
}
return 0;
}
the function call to bruteForce
int f_solveSudoku(s_cellBoard board[9][9])
{
int arr_32[513] = { 0 };
initialization32Arr(arr_32);
int i = 0;
while (board[i / 9][i % 9].isGiven) { i++; }
return bruteForce(board, i, arr_32);
}
functions to check the block
int block(s_cellBoard board[9][9], int i, int num) {
for (int b, a = 0; a < 3; a++)
{
for (b = 0; b < 3; b++)
{
if (board[((i / 9) - ((i / 9) % 3)) + a][((i % 9) - ((i % 9) % 3)) + b].value == num)
return 0;
}
}
return 1;
}
functions to check the column
int col(s_cellBoard board[9][9], int i, int num) {
int j;
for (j = 0; j < 9; j++)
{
if (board[j][i % 9].value == num)
return 0;
}
return 1;
}
functions to check the row
int row(s_cellBoard board[9][9], int i, int num) {
int j;
for (j = 0; j < 9; j++)
{
if (board[i / 9][j].value == num)
return 0;
}
return 1;
}
The following modification to the bruteForce function should work. I'm not sure what the arr_32[] parameter is for, as it does not seem to be used.
int bruteForce(s_cellBoard board[9][9], int i, int arr_32[]) {
// skip cells with 'given' numbers
while (i < 81 && board[i / 9][i % 9].isGiven)
i++;
if (i == 81)
return 1; // done all the cells, so solution found
// check numbers 1 to 9 for current cell
while (isPossible(board, i, arr_32))
{
// found a possible number for the cell
// so check remaining cells
if (bruteForce(board, i + 1, arr_32))
return 1; // solution found
}
// tried all the numbers for this cell without finding a solution
board[i / 9][i % 9].value = 0; // reset the cell
return 0; // solution not yet found
}
I made a working sudoku solver using a basic backtracking algorithm.
It works reasonably well even though there are many optimizations to be done.
I tried modifying my code to return the total number of solutions for a given sudoku grid. To do this I simply changed the solving function to add up every possibility instead of stopping at one.
However I only get 1 or 0.
Here is the code for the basic solver:
int check_row(char **tab, int y, int n)
{
int i;
i = 0;
while (i < 9)
{
if (tab[y][i] == n + '0')
return (0);
i++;
}
return (1);
}
int check_column(char **tab, int x, int n)
{
int j;
j = 0;
while (j < 9)
{
if (tab[j][x] == n + '0')
return (0);
j++;
}
return (1);
}
int check_square(char **tab, int x, int y, int n)
{
int i;
int j;
i = (x / 3) * 3;
while (i < (x / 3) * 3 + 3)
{
j = (y / 3) * 3;
while (j < (y / 3) * 3 + 3)
{
if (tab[j][i] == n + '0')
return (0);
j++;
}
i++;
}
return (1);
}
int solve(char **tab, int x, int y)
{
int n;
if (y >= 9 || x >= 9)
return (1);
if (tab[y][x] == '.')
{
n = 1;
while (n < 10)
{
if (check_row(tab, y, n) && check_column(tab, x, n)
&& check_square(tab, x, y, n))
{
tab[y][x] = n + '0';
if (solve(tab, (x + 1) % 9, y + ((x + 1) / 9)))
return (1);
}
n++;
}
tab[y][x] = '.';
return (0);
}
else
return (solve(tab, (x + 1) % 9, y + ((x + 1) / 9)));
}
And here is the modified function that should count the solutions:
int solve_count(char **tab, int x, int y)
{
int n;
int count;
count = 0;
if (y >= 9 || x >= 9)
return (1);
if (tab[y][x] == '.')
{
n = 1;
while (n < 10)
{
if (check_row(tab, y, n) && check_column(tab, x, n)
&& check_square(tab, x, y, n))
{
tab[y][x] = n + '0';
count += solve_count(tab, (x + 1) % 9, y + ((x + 1) / 9));
}
n++;
}
tab[y][x] = '.';
return (count);
}
else
return (solve_count(tab, (x + 1) % 9, y + ((x + 1) / 9)));
}
The main() and helper functions are as follows:
#include <unistd.h>
int solve(char **tab, int x, int y);
int solve_count(char **tab, int x, int y);
void ft_putchar(char c)
{
write(1, &c, 1);
}
void ft_putstr(char *str)
{
int i;
i = 0;
while (*(str + i) != '\0')
{
ft_putchar(*(str + i));
i++;
}
}
void ft_putnbr(int n)
{
int i;
int vect[20];
long nb;
nb = n;
i = -1;
if (nb < 0)
{
ft_putchar('-');
nb = -nb;
}
if (nb == 0)
ft_putchar('0');
while (nb > 0)
{
i++;
vect[i] = nb % 10;
nb = nb / 10;
}
while (i > -1)
{
ft_putchar('0' + vect[i]);
i--;
}
}
int ft_check_input(int argc, char **argv)
{
int i;
int j;
i = 1;
j = 0;
if (argc != 10)
return (1);
while (i < argc)
{
while (argv[i][j])
j++;
if (j != 9)
return (1);
j = 0;
while (argv[i][j] == '.' || (argv[i][j] > '0' && argv[i][j] <= '9'))
j++;
if (j != 9)
return (1);
j = 0;
i++;
}
if (i != 10)
return (1);
else
return (0);
}
void ft_print_sudoku(char **tab)
{
int i;
int j;
i = 1;
j = 0;
while (i < 10)
{
while (j < 9)
{
ft_putchar(tab[i][j]);
if (j < 8)
ft_putchar(' ');
j++;
}
ft_putchar('\n');
j = 0;
i++;
}
}
int main(int argc, char **argv)
{
if (ft_check_input(argc, argv))
ft_putstr("Error: not a good sudoku\n");
else
{
if (solve(argv + 1, 0, 0))
{
ft_print_sudoku(argv);
ft_putnbr(solve_count(argv + 1, 0, 0));
}
else
ft_putstr("Error: no solution\n");
}
return (0);
}
To get the number of solutions for an empty sudoku you would run ('.' means empty item):
./sudoku "........." "........." "........." "........." "........." "........." "........." "........." "........."
It runs, but still stops at the first solution it finds, and returns 1.
What am I missing? I've been scratching my head for a while now.
Eventually I'm thinking of using this function to create a grid by adding random numbers until there's just one solution.
I Did this a long time ago for fun...
What I did to Solve the most difficult ones was to return for each squares, All possible numbers
And then destroy each possible numbers one by one for each grid...
so even if you get 9 possibilities for the first grid you enter the first and if it doesn't fit. you delete it and try the second.
One of them needs too fit :)
To know how may possible solutions to a soduku puzzle exists that would take a brute force calculation.