Количество N-значных целых чисел веса W
Дано N, количество цифр целого числа, которое больше или равно 2, и вес W. Задача состоит в том, чтобы найти количество целых чисел, состоящих из N цифр и веса W.
Примечание . Вес определяется как разница между последовательными цифрами целого числа.
Примеры :
Ввод: N = 2, W = 3 Выход: 6 Ввод: N = 2, W = 4 Выход: 5
В приведенном выше примере общее количество возможных 2-значных целых чисел с весом, равным 3, будет 6. Так же, как число 14 имеет вес 3 (4-1), а 25, 36, 47, 58, 69 имеет вес 3. Если мы видим Мы тщательно найдем логику, согласно которой, если мы увеличим вес 2-значного числа на 5, то общее количество возможных таких чисел будет 5. При весе 6 для 2-значного числа общее количество возможных чисел будет равно 4 а потом 3 и так далее. Также, если увеличить количество цифр. Скажем, n равно 3 с весом 3, тогда общее количество возможных чисел будет 60 и 600 для n, равного 4, с весом 3 и так далее.
Количество цифр | Вес -> Всего возможных таких чисел 2 | 2 -> 7 2 | 3 -> 6 2 | 4 -> 5 2 | 5 -> 4 2 | 6 -> 3 2 | 7 -> 2 2 | 8 -> 1 3 | 2 -> 70 3 | 3 -> 60 3 | 4 -> 50 3 | 5 -> 40 3 | 6 -> 30 3 | 7 -> 20 3 | 8 -> 10 4 | 2 -> 700 4 | 3 -> 600 4 | 4 -> 500 4 | 5 -> 400 4 | 6 -> 300 4 | 7 -> 200 4 | 8 -> 100
Как вы можете видеть в приведенной выше таблице, с увеличением количества цифр количество чисел с весом 'w' следует шаблону, где оно изменяется кратно 10 ^ (n-2), где ' n '- количество цифр.
Ниже приведен пошаговый алгоритм решения этой проблемы:
- Проверьте, является ли данный вес (W) положительным или отрицательным.
- Вычтите вес (W) из 9, если он положительный.
- Добавьте вес к 10, если он отрицательный, а затем обновите новый вес.
- Для n-значного целого числа умножьте 10 ^ (n-2) на этот обновленный вес.
- Это даст нам количество целых чисел, удовлетворяющих этому весу.
Below is the implementation of above approach:
C++
// CPP program to find total possible numbers // with n digits and weight w #include <iostream> #include<cmath> using namespace std; // Function to find total possible numbers // with n digits and weight w int findNumbers( int n, int w) { int x = 0, sum = 0; // When Weight of an integer is Positive if (w >= 0 && w <= 8) { // Subtract the weight from 9 x = 9 - w; } // When weight of an integer is negative else if (w >= -9 && w <= -1) { // add the weight to 10 to make it positive x = 10 + w; } sum = pow (10, n - 2); sum = (x * sum); return sum; } // Driver code int main() { int n, w; // number of digits in an // integer and w as weight n = 3, w = 4; // print the total possible numbers // with n digits and weight w cout << findNumbers(n, w);; return 0; } |
Java
// Java program to find total // possible numbers with n // digits and weight w class GFG { // Function to find total // possible numbers with n // digits and weight w static int findNumbers( int n, int w) { int x = 0 , sum = 0 ; // When Weight of an // integer is Positive if (w >= 0 && w <= 8 ) { // Subtract the weight from 9 x = 9 - w; } // When weight of an // integer is negative else if (w >= - 9 && w <= - 1 ) { // add the weight to 10 // to make it positive x = 10 + w; } sum = ( int )Math.pow( 10 , n - 2 ); sum = (x * sum); return sum; } // Driver code public static void main(String args[]) { int n, w; // number of digits in an // integer and w as weight n = 3 ; w = 4 ; // print the total possible numbers // with n digits and weight w System.out.println(findNumbers(n, w)); } } // This code is contributed // by ankita_saini |
Python3
# Python3 program to find total possible # numbers with n digits and weight w # Function to find total possible # numbers with n digits and weight w def findNumbers(n, w): x = 0 ; sum = 0 ; # When Weight of an integer # is Positive if (w > = 0 and w < = 8 ): # Subtract the weight from 9 x = 9 - w; # When weight of an integer # is negative elif (w > = - 9 and w < = - 1 ): # add the weight to 10 to # make it positive x = 10 + w; sum = pow ( 10 , n - 2 ); sum = (x * sum ); return sum ; # Driver code # number of digits in an # integer and w as weight n = 3 ; w = 4 ; # print the total possible numbers # with n digits and weight w print (findNumbers(n, w)); # This code is contributed # by mits |
C#
// C# program to find total possible // numbers with n digits and weight w using System; class GFG { // Function to find total possible // numbers with n digits and weight w static int findNumbers( int n, int w) { int x = 0, sum = 0; // When Weight of an integer // is Positive if (w >= 0 && w <= 8) { // Subtract the weight from 9 x = 9 - w; } // When weight of an // integer is negative else if (w >= -9 && w <= -1) { // add the weight to 10 // to make it positive x = 10 + w; } sum = ( int )Math.Pow(10, n - 2); sum = (x * sum); return sum; } // Driver code static public void Main () { int n, w; // number of digits in an // integer and w as weight n = 3; w = 4; // print the total possible numbers // with n digits and weight w Console.WriteLine(findNumbers(n, w)); } } // This code is contributed by jit_t |
PHP
<?php // PHP program to find total possible // numbers with n digits and weight w // Function to find total possible // numbers with n digits and weight w function findNumbers( $n , $w ) { $x = 0; $sum = 0; // When Weight of an integer // is Positive if ( $w >= 0 && $w <= 8) { // Subtract the weight from 9 $x = 9 - $w ; } // When weight of an integer // is negative else if ( $w >= -9 && $w <= -1) { // add the weight to 10 to // make it positive $x = 10 + $w ; } $sum = pow(10, $n - 2); $sum = ( $x * $sum ); return $sum ; } // Driver code // number of digits in an // integer and w as weight $n = 3; $w = 4; // print the total possible numbers // with n digits and weight w echo findNumbers( $n , $w ); // This code is contributed // by Akanksha Rai |
Javascript
<script> // Javascript program to find total possible // numbers with n digits and weight w // Function to find total possible // numbers with n digits and weight w function findNumbers(n, w) { let x = 0, sum = 0; // When Weight of an integer // is Positive if (w >= 0 && w <= 8) { // Subtract the weight from 9 x = 9 - w; } // When weight of an // integer is negative else if (w >= -9 && w <= -1) { // add the weight to 10 // to make it positive x = 10 + w; } sum = Math.pow(10, n - 2); sum = (x * sum); return sum; } let n, w; // number of digits in an // integer and w as weight n = 3; w = 4; // print the total possible numbers // with n digits and weight w document.write(findNumbers(n, w)); </script> |
50
Вниманию читателя! Не прекращайте учиться сейчас. Получите все важные математические концепции для соревновательного программирования с курсом Essential Maths for CP по доступной для студентов цене. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .