Проверить делимость на 7
Given a number, check if it is divisible by 7. You are not allowed to use modulo operator, floating point arithmetic is also not allowed.
A simple method is repeated subtraction. Following is another interesting method.
Divisibility by 7 can be checked by a recursive method. A number of the form 10a + b is divisible by 7 if and only if a – 2b is divisible by 7. In other words, subtract twice the last digit from the number formed by the remaining digits. Continue to do this until a small number.
Example: the number 371: 37 – (2×1) = 37 – 2 = 35; 3 – (2 × 5) = 3 – 10 = -7; thus, since -7 is divisible by 7, 371 is divisible by 7.
Following is the implementation of the above method
C++
// A Program to check whether a number is divisible by 7#include <bits/stdc++.h>using namespace std;int isDivisibleBy7( int num ){ // If number is negative, make it positive if( num < 0 ) return isDivisibleBy7( -num ); // Base cases if( num == 0 || num == 7 ) return 1; if( num < 10 ) return 0; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) );}// Driver codeint main(){ int num = 616; if( isDivisibleBy7(num ) ) cout << "Divisible" ; else cout << "Not Divisible" ; return 0;}// This code is contributed by rathbhupendra |
C
// A Program to check whether a number is divisible by 7#include <stdio.h>int isDivisibleBy7( int num ){ // If number is negative, make it positive if( num < 0 ) return isDivisibleBy7( -num ); // Base cases if( num == 0 || num == 7 ) return 1; if( num < 10 ) return 0; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) );}// Driver program to test above functionint main(){ int num = 616; if( isDivisibleBy7(num ) ) printf( "Divisible" ); else printf( "Not Divisible" ); return 0;} |
Java
// Java program to check whether a number is divisible by 7import java.io.*;class GFG{ // Function to check whether a number is divisible by 7 static boolean isDivisibleBy7(int num) { // If number is negative, make it positive if( num < 0 ) return isDivisibleBy7( -num ); // Base cases if( num == 0 || num == 7 ) return true; if( num < 10 ) return false; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) ); } // Driver program public static void main (String[] args) { int num = 616; if(isDivisibleBy7(num)) System.out.println("Divisible"); else System.out.println("Not Divisible"); }}// Contributed by Pramod Kumar |
Python
# Python program to check whether a number is divisible by 7# Function to check whether a number is divisible by 7def isDivisibleBy7(num) : # If number is negative, make it positive if num < 0 : return isDivisibleBy7( -num ) # Base cases if( num == 0 or num == 7 ) : return True if( num < 10 ) : return False # Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) ) # Driver programnum = 616if(isDivisibleBy7(num)) : print "Divisible"else : print "Not Divisible"# This code is contributed by Nikita Tiwari |
C#
// C# program to check whether a// number is divisible by 7using System;class GFG { // Function to check whether a // number is divisible by 7 static bool isDivisibleBy7(int num) { // If number is negative, // make it positive if( num < 0 ) return isDivisibleBy7(-num); // Base cases if( num == 0 || num == 7 ) return true; if( num < 10 ) return false; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7(num / 10 - 2 * ( num - num / 10 * 10 )); } // Driver Code public static void Main () { int num = 616; if(isDivisibleBy7(num)) Console.Write("Divisible"); else Console.Write("Not Divisible"); }}// This code is contributed by Nitin Mittal. |
PHP
<?php// PHP Program to check whether// a number is divisible by 7// Function to check whether a// number is divisible by 7function isDivisibleBy7( $num ){ // If number is negative, // make it positive if( $num < 0 ) return isDivisibleBy7( -$num ); // Base cases if( $num == 0 || $num == 7 ) return 1; if( $num < 10 ) return 0; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7($num / 10 - 2 * ($num - $num / 10 * 10 ) );} // Driver Code $num = 616; if( isDivisibleBy7($num )>=0 ) echo("Divisible"); else echo("Not Divisible"); // This code is contributed by vt_m.?> |
Javascript
<script>// js Program to check whether// a number is divisible by 7// Function to check whether a// number is divisible by 7function isDivisibleBy7( num ){ // If number is negative, // make it positive if( num < 0 ) return isDivisibleBy7( -num ); // Base cases if( num == 0 || num == 7 ) return 1; if( num < 10 ) return 0; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7(num / 10 - 2 * (num - num / 10 * 10 ) );} // Driver Code let num = 616; if( isDivisibleBy7(num )>=0 ) document.write("Divisible"); else document.write("Not Divisible"); // This code is contributed by sravan kumar</script> |
Выход:
Делимый
Как это работает? Пусть «b» будет последней цифрой числа «n», а «a» будет числом, которое мы получим, когда разделим «b».
Представление числа также может быть умножено на любое число, относительно простое с делителем, без изменения его делимости. Заметив, что 7 делит 21, мы можем выполнить следующее:
10. а + б
после умножения на 2 это становится
20.a + 2.b
а потом
21.a - a + 2.b
Исключение кратного 21 дает
-a + 2b
и умножение на -1 дает
а - 2б
Есть и другие интересные методы проверки делимости на 7 и другие числа. См. Дополнительную информацию на следующей странице Wiki.
Использованная литература:
http://en.wikipedia.org/wiki/Divisibility_rule
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.
Вниманию читателя! Не прекращайте учиться сейчас. Получите все важные математические концепции для соревновательного программирования с курсом Essential Maths for CP по доступной для студентов цене. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .